ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.212
Committed: Sat Jul 12 15:34:10 2014 UTC (9 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.211: +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 jsr166 1.156 import java.lang.Thread.UncaughtExceptionHandler;
10 jsr166 1.1 import java.util.ArrayList;
11     import java.util.Arrays;
12     import java.util.Collection;
13     import java.util.Collections;
14     import java.util.List;
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 dl 1.178 import java.util.concurrent.ThreadLocalRandom;
22 dl 1.36 import java.util.concurrent.TimeUnit;
23 dl 1.197 import java.security.AccessControlContext;
24     import java.security.ProtectionDomain;
25     import java.security.Permissions;
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 dl 1.112 * <p>A static {@link #commonPool()} is available and appropriate for
46 dl 1.101 * most applications. The common pool is used by any ForkJoinTask that
47     * is not explicitly submitted to a specified pool. Using the common
48     * pool normally reduces resource usage (its threads are slowly
49     * reclaimed during periods of non-use, and reinstated upon subsequent
50 dl 1.105 * use).
51 dl 1.100 *
52     * <p>For applications that require separate or custom pools, a {@code
53     * ForkJoinPool} may be constructed with a given target parallelism
54     * level; by default, equal to the number of available processors. The
55     * pool attempts to maintain enough active (or available) threads by
56     * dynamically adding, suspending, or resuming internal worker
57 jsr166 1.187 * threads, even if some tasks are stalled waiting to join others.
58     * However, no such adjustments are guaranteed in the face of blocked
59     * I/O or other unmanaged synchronization. The nested {@link
60 dl 1.100 * ManagedBlocker} interface enables extension of the kinds of
61 dl 1.18 * synchronization accommodated.
62 jsr166 1.1 *
63     * <p>In addition to execution and lifecycle control methods, this
64     * class provides status check methods (for example
65 jsr166 1.4 * {@link #getStealCount}) that are intended to aid in developing,
66 jsr166 1.1 * tuning, and monitoring fork/join applications. Also, method
67 jsr166 1.4 * {@link #toString} returns indications of pool state in a
68 jsr166 1.1 * convenient form for informal monitoring.
69     *
70 jsr166 1.109 * <p>As is the case with other ExecutorServices, there are three
71 jsr166 1.84 * main task execution methods summarized in the following table.
72     * These are designed to be used primarily by clients not already
73     * engaged in fork/join computations in the current pool. The main
74     * forms of these methods accept instances of {@code ForkJoinTask},
75     * but overloaded forms also allow mixed execution of plain {@code
76     * Runnable}- or {@code Callable}- based activities as well. However,
77     * tasks that are already executing in a pool should normally instead
78     * use the within-computation forms listed in the table unless using
79     * async event-style tasks that are not usually joined, in which case
80     * there is little difference among choice of methods.
81 dl 1.18 *
82     * <table BORDER CELLPADDING=3 CELLSPACING=1>
83 jsr166 1.159 * <caption>Summary of task execution methods</caption>
84 dl 1.18 * <tr>
85     * <td></td>
86     * <td ALIGN=CENTER> <b>Call from non-fork/join clients</b></td>
87     * <td ALIGN=CENTER> <b>Call from within fork/join computations</b></td>
88     * </tr>
89     * <tr>
90 jsr166 1.153 * <td> <b>Arrange async execution</b></td>
91 dl 1.18 * <td> {@link #execute(ForkJoinTask)}</td>
92     * <td> {@link ForkJoinTask#fork}</td>
93     * </tr>
94     * <tr>
95 jsr166 1.153 * <td> <b>Await and obtain result</b></td>
96 dl 1.18 * <td> {@link #invoke(ForkJoinTask)}</td>
97     * <td> {@link ForkJoinTask#invoke}</td>
98     * </tr>
99     * <tr>
100 jsr166 1.153 * <td> <b>Arrange exec and obtain Future</b></td>
101 dl 1.18 * <td> {@link #submit(ForkJoinTask)}</td>
102     * <td> {@link ForkJoinTask#fork} (ForkJoinTasks <em>are</em> Futures)</td>
103     * </tr>
104     * </table>
105 dl 1.19 *
106 dl 1.105 * <p>The common pool is by default constructed with default
107 jsr166 1.155 * parameters, but these may be controlled by setting three
108 jsr166 1.162 * {@linkplain System#getProperty system properties}:
109     * <ul>
110     * <li>{@code java.util.concurrent.ForkJoinPool.common.parallelism}
111     * - the parallelism level, a non-negative integer
112     * <li>{@code java.util.concurrent.ForkJoinPool.common.threadFactory}
113     * - the class name of a {@link ForkJoinWorkerThreadFactory}
114     * <li>{@code java.util.concurrent.ForkJoinPool.common.exceptionHandler}
115     * - the class name of a {@link UncaughtExceptionHandler}
116 dl 1.208 * <li>{@code java.util.concurrent.ForkJoinPool.common.maximumSpares}
117     * - the maximum number of alloed extra threads to maintain target
118     * parallelism (default 256).
119 jsr166 1.162 * </ul>
120 dl 1.197 * If a {@link SecurityManager} is present and no factory is
121     * specified, then the default pool uses a factory supplying
122     * threads that have no {@link Permissions} enabled.
123 jsr166 1.165 * The system class loader is used to load these classes.
124 jsr166 1.156 * Upon any error in establishing these settings, default parameters
125 dl 1.160 * are used. It is possible to disable or limit the use of threads in
126     * the common pool by setting the parallelism property to zero, and/or
127 dl 1.193 * using a factory that may return {@code null}. However doing so may
128     * cause unjoined tasks to never be executed.
129 dl 1.105 *
130 jsr166 1.1 * <p><b>Implementation notes</b>: This implementation restricts the
131     * maximum number of running threads to 32767. Attempts to create
132 jsr166 1.11 * pools with greater than the maximum number result in
133 jsr166 1.8 * {@code IllegalArgumentException}.
134 jsr166 1.1 *
135 jsr166 1.11 * <p>This implementation rejects submitted tasks (that is, by throwing
136 dl 1.19 * {@link RejectedExecutionException}) only when the pool is shut down
137 dl 1.20 * or internal resources have been exhausted.
138 jsr166 1.11 *
139 jsr166 1.1 * @since 1.7
140     * @author Doug Lea
141     */
142 jsr166 1.171 @sun.misc.Contended
143 jsr166 1.1 public class ForkJoinPool extends AbstractExecutorService {
144    
145     /*
146 dl 1.14 * Implementation Overview
147     *
148 dl 1.78 * This class and its nested classes provide the main
149     * functionality and control for a set of worker threads:
150 jsr166 1.84 * Submissions from non-FJ threads enter into submission queues.
151     * Workers take these tasks and typically split them into subtasks
152     * that may be stolen by other workers. Preference rules give
153     * first priority to processing tasks from their own queues (LIFO
154     * or FIFO, depending on mode), then to randomized FIFO steals of
155 dl 1.200 * tasks in other queues. This framework began as vehicle for
156     * supporting tree-structured parallelism using work-stealing.
157     * Over time, its scalability advantages led to extensions and
158 dl 1.208 * changes to better support more diverse usage contexts. Because
159     * most internal methods and nested classes are interrelated,
160     * their main rationale and descriptions are presented here;
161     * individual methods and nested classes contain only brief
162     * comments about details.
163 dl 1.78 *
164 jsr166 1.84 * WorkQueues
165 dl 1.78 * ==========
166     *
167     * Most operations occur within work-stealing queues (in nested
168     * class WorkQueue). These are special forms of Deques that
169     * support only three of the four possible end-operations -- push,
170     * pop, and poll (aka steal), under the further constraints that
171     * push and pop are called only from the owning thread (or, as
172     * extended here, under a lock), while poll may be called from
173     * other threads. (If you are unfamiliar with them, you probably
174     * want to read Herlihy and Shavit's book "The Art of
175     * Multiprocessor programming", chapter 16 describing these in
176     * more detail before proceeding.) The main work-stealing queue
177     * design is roughly similar to those in the papers "Dynamic
178     * Circular Work-Stealing Deque" by Chase and Lev, SPAA 2005
179     * (http://research.sun.com/scalable/pubs/index.html) and
180     * "Idempotent work stealing" by Michael, Saraswat, and Vechev,
181     * PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186).
182 dl 1.200 * The main differences ultimately stem from GC requirements that
183     * we null out taken slots as soon as we can, to maintain as small
184     * a footprint as possible even in programs generating huge
185     * numbers of tasks. To accomplish this, we shift the CAS
186     * arbitrating pop vs poll (steal) from being on the indices
187     * ("base" and "top") to the slots themselves.
188     *
189     * Adding tasks then takes the form of a classic array push(task):
190     * q.array[q.top] = task; ++q.top;
191     *
192     * (The actual code needs to null-check and size-check the array,
193     * properly fence the accesses, and possibly signal waiting
194     * workers to start scanning -- see below.) Both a successful pop
195     * and poll mainly entail a CAS of a slot from non-null to null.
196     *
197 jsr166 1.202 * The pop operation (always performed by owner) is:
198 dl 1.200 * if ((base != top) and
199     * (the task at top slot is not null) and
200     * (CAS slot to null))
201     * decrement top and return task;
202     *
203     * And the poll operation (usually by a stealer) is
204     * if ((base != top) and
205     * (the task at base slot is not null) and
206     * (base has not changed) and
207     * (CAS slot to null))
208     * increment base and return task;
209     *
210     * Because we rely on CASes of references, we do not need tag bits
211     * on base or top. They are simple ints as used in any circular
212 dl 1.170 * array-based queue (see for example ArrayDeque). Updates to the
213 dl 1.200 * indices guarantee that top == base means the queue is empty,
214     * but otherwise may err on the side of possibly making the queue
215     * appear nonempty when a push, pop, or poll have not fully
216 dl 1.205 * committed. (Method isEmpty() checks the case of a partially
217 dl 1.211 * completed removal of the last element.) Because of this, the
218     * poll operation, considered individually, is not wait-free. One
219     * thief cannot successfully continue until another in-progress
220     * one (or, if previously empty, a push) completes. However, in
221     * the aggregate, we ensure at least probabilistic
222 dl 1.205 * non-blockingness. If an attempted steal fails, a thief always
223     * chooses a different random victim target to try next. So, in
224     * order for one thief to progress, it suffices for any
225     * in-progress poll or new push on any empty queue to
226     * complete. (This is why we normally use method pollAt and its
227     * variants that try once at the apparent base index, else
228     * consider alternative actions, rather than method poll, which
229     * retries.)
230 dl 1.200 *
231     * This approach also enables support of a user mode in which
232     * local task processing is in FIFO, not LIFO order, simply by
233     * using poll rather than pop. This can be useful in
234     * message-passing frameworks in which tasks are never joined.
235     * However neither mode considers affinities, loads, cache
236     * localities, etc, so rarely provide the best possible
237     * performance on a given machine, but portably provide good
238     * throughput by averaging over these factors. Further, even if
239     * we did try to use such information, we do not usually have a
240     * basis for exploiting it. For example, some sets of tasks
241     * profit from cache affinities, but others are harmed by cache
242     * pollution effects. Additionally, even though it requires
243     * scanning, long-term throughput is often best using random
244     * selection rather than directed selection policies, so cheap
245     * randomization of sufficient quality is used whenever
246     * applicable. Various Marsaglia XorShifts (some with different
247     * shift constants) are inlined at use points.
248 dl 1.78 *
249     * WorkQueues are also used in a similar way for tasks submitted
250     * to the pool. We cannot mix these tasks in the same queues used
251 dl 1.200 * by workers. Instead, we randomly associate submission queues
252 dl 1.83 * with submitting threads, using a form of hashing. The
253 dl 1.139 * ThreadLocalRandom probe value serves as a hash code for
254     * choosing existing queues, and may be randomly repositioned upon
255     * contention with other submitters. In essence, submitters act
256     * like workers except that they are restricted to executing local
257     * tasks that they submitted (or in the case of CountedCompleters,
258 dl 1.200 * others with the same root task). Insertion of tasks in shared
259 dl 1.139 * mode requires a lock (mainly to protect in the case of
260 dl 1.200 * resizing) but we use only a simple spinlock (using field
261     * qlock), because submitters encountering a busy queue move on to
262     * try or create other queues -- they block only when creating and
263 dl 1.211 * registering new queues. Additionally, "qlock" saturates to an
264     * unlockable value (-1) at shutdown. Unlocking still can be and
265     * is performed by cheaper ordered writes of "qlock" in successful
266     * cases, but uses CAS in unsuccessful cases.
267 dl 1.78 *
268 jsr166 1.84 * Management
269 dl 1.78 * ==========
270 dl 1.52 *
271     * The main throughput advantages of work-stealing stem from
272     * decentralized control -- workers mostly take tasks from
273 dl 1.200 * themselves or each other, at rates that can exceed a billion
274     * per second. The pool itself creates, activates (enables
275     * scanning for and running tasks), deactivates, blocks, and
276     * terminates threads, all with minimal central information.
277     * There are only a few properties that we can globally track or
278     * maintain, so we pack them into a small number of variables,
279     * often maintaining atomicity without blocking or locking.
280     * Nearly all essentially atomic control state is held in two
281     * volatile variables that are by far most often read (not
282     * written) as status and consistency checks.
283 dl 1.78 *
284 dl 1.200 * Field "ctl" contains 64 bits holding information needed to
285     * atomically decide to add, inactivate, enqueue (on an event
286 dl 1.78 * queue), dequeue, and/or re-activate workers. To enable this
287     * packing, we restrict maximum parallelism to (1<<15)-1 (which is
288     * far in excess of normal operating range) to allow ids, counts,
289     * and their negations (used for thresholding) to fit into 16bit
290 dl 1.200 * subfields. Field "runState" holds lockable state bits
291     * (STARTED, STOP, etc) also protecting updates to the workQueues
292     * array. When used as a lock, it is normally held only for a few
293     * instructions (the only exceptions are one-time array
294     * initialization and uncommon resizing), so is nearly always
295     * available after at most a brief spin. But to be extra-cautious,
296     * we use a monitor-based backup strategy to block when needed
297     * (see awaitRunStateLock). Usages of "runState" vs "ctl"
298     * interact in only one case: deciding to add a worker thread (see
299     * tryAddWorker), in which case the ctl CAS is performed while the
300     * lock is held. Field "config" holds unchanging configuration
301     * state.
302 dl 1.78 *
303     * Recording WorkQueues. WorkQueues are recorded in the
304 dl 1.200 * "workQueues" array. The array is created upon first use (see
305     * externalSubmit) and expanded if necessary. Updates to the
306     * array while recording new workers and unrecording terminated
307     * ones are protected from each other by the runState lock, but
308     * the array is otherwise concurrently readable, and accessed
309     * directly. We also ensure that reads of the array reference
310     * itself never become too stale. To simplify index-based
311     * operations, the array size is always a power of two, and all
312     * readers must tolerate null slots. Worker queues are at odd
313     * indices. Shared (submission) queues are at even indices, up to
314     * a maximum of 64 slots, to limit growth even if array needs to
315     * expand to add more workers. Grouping them together in this way
316     * simplifies and speeds up task scanning.
317 dl 1.86 *
318     * All worker thread creation is on-demand, triggered by task
319     * submissions, replacement of terminated workers, and/or
320 dl 1.78 * compensation for blocked workers. However, all other support
321     * code is set up to work with other policies. To ensure that we
322 dl 1.200 * do not hold on to worker references that would prevent GC, All
323 dl 1.78 * accesses to workQueues are via indices into the workQueues
324     * array (which is one source of some of the messy code
325     * constructions here). In essence, the workQueues array serves as
326 dl 1.200 * a weak reference mechanism. Thus for example the stack top
327     * subfield of ctl stores indices, not references.
328     *
329     * Queuing Idle Workers. Unlike HPC work-stealing frameworks, we
330     * cannot let workers spin indefinitely scanning for tasks when
331     * none can be found immediately, and we cannot start/resume
332     * workers unless there appear to be tasks available. On the
333     * other hand, we must quickly prod them into action when new
334     * tasks are submitted or generated. In many usages, ramp-up time
335     * to activate workers is the main limiting factor in overall
336     * performance, which is compounded at program start-up by JIT
337     * compilation and allocation. So we streamline this as much as
338     * possible.
339     *
340     * The "ctl" field atomically maintains active and total worker
341     * counts as well as a queue to place waiting threads so they can
342     * be located for signalling. Active counts also play the role of
343     * quiescence indicators, so are decremented when workers believe
344     * that there are no more tasks to execute. The "queue" is
345     * actually a form of Treiber stack. A stack is ideal for
346     * activating threads in most-recently used order. This improves
347     * performance and locality, outweighing the disadvantages of
348     * being prone to contention and inability to release a worker
349     * unless it is topmost on stack. We park/unpark workers after
350     * pushing on the idle worker stack (represented by the lower
351     * 32bit subfield of ctl) when they cannot find work. The top
352     * stack state holds the value of the "scanState" field of the
353     * worker: its index and status, plus a version counter that, in
354     * addition to the count subfields (also serving as version
355     * stamps) provide protection against Treiber stack ABA effects.
356     *
357     * Field scanState is used by both workers and the pool to manage
358     * and track whether a worker is INACTIVE (possibly blocked
359     * waiting for a signal), or SCANNING for tasks (when neither hold
360     * it is busy running tasks). When a worker is inactivated, its
361     * scanState field is set, and is prevented from executing tasks,
362     * even though it must scan once for them to avoid queuing
363     * races. Note that scanState updates lag queue CAS releases so
364     * usage requires care. When queued, the lower 16 bits of
365     * scanState must hold its pool index. So we place the index there
366     * upon initialization (see registerWorker) and otherwise keep it
367     * there or restore it when necessary.
368     *
369     * Memory ordering. See "Correct and Efficient Work-Stealing for
370     * Weak Memory Models" by Le, Pop, Cohen, and Nardelli, PPoPP 2013
371     * (http://www.di.ens.fr/~zappa/readings/ppopp13.pdf) for an
372     * analysis of memory ordering requirements in work-stealing
373     * algorithms similar to the one used here. We usually need
374     * stronger than minimal ordering because we must sometimes signal
375     * workers, requiring Dekker-like full-fences to avoid lost
376     * signals. Arranging for enough ordering without expensive
377     * over-fencing requires tradeoffs among the supported means of
378     * expressing access constraints. The most central operations,
379     * taking from queues and updating ctl state, require full-fence
380     * CAS. Array slots are read using the emulation of volatiles
381     * provided by Unsafe. Access from other threads to WorkQueue
382     * base, top, and array requires a volatile load of the first of
383     * any of these read. We use the convention of declaring the
384     * "base" index volatile, and always read it before other fields.
385     * The owner thread must ensure ordered updates, so writes use
386     * ordered intrinsics unless they can piggyback on those for other
387     * writes. Similar conventions and rationales hold for other
388     * WorkQueue fields (such as "currentSteal") that are only written
389     * by owners but observed by others.
390     *
391     * Creating workers. To create a worker, we pre-increment total
392     * count (serving as a reservation), and attempt to construct a
393     * ForkJoinWorkerThread via its factory. Upon construction, the
394     * new thread invokes registerWorker, where it constructs a
395     * WorkQueue and is assigned an index in the workQueues array
396     * (expanding the array if necessary). The thread is then
397     * started. Upon any exception across these steps, or null return
398     * from factory, deregisterWorker adjusts counts and records
399     * accordingly. If a null return, the pool continues running with
400     * fewer than the target number workers. If exceptional, the
401     * exception is propagated, generally to some external caller.
402     * Worker index assignment avoids the bias in scanning that would
403     * occur if entries were sequentially packed starting at the front
404     * of the workQueues array. We treat the array as a simple
405     * power-of-two hash table, expanding as needed. The seedIndex
406     * increment ensures no collisions until a resize is needed or a
407     * worker is deregistered and replaced, and thereafter keeps
408 jsr166 1.202 * probability of collision low. We cannot use
409 dl 1.200 * ThreadLocalRandom.getProbe() for similar purposes here because
410     * the thread has not started yet, but do so for creating
411     * submission queues for existing external threads.
412     *
413 jsr166 1.202 * Deactivation and waiting. Queuing encounters several intrinsic
414 dl 1.200 * races; most notably that a task-producing thread can miss
415     * seeing (and signalling) another thread that gave up looking for
416     * work but has not yet entered the wait queue. When a worker
417     * cannot find a task to steal, it deactivates and enqueues. Very
418     * often, the lack of tasks is transient due to GC or OS
419     * scheduling. To reduce false-alarm deactivation, scanners
420 dl 1.211 * compute checksums of queue states during sweeps. (The
421 jsr166 1.212 * stability checks used here and elsewhere are probabilistic
422 dl 1.211 * variants of snapshot techniques -- see Herlihy & Shavit.)
423     * Workers give up and try to deactivate only after the sum is
424     * stable across scans. Further, to avoid missed signals, they
425     * repeat this scanning process after successful enqueuing until
426     * again stable. In this state, the worker cannot take/run a task
427     * it sees until it is released from the queue, so the worker
428     * itself eventually tries to release itself or any successor (see
429     * tryRelease). Otherwise, upon an empty scan, a deactivated
430     * worker uses an adaptive local spin construction (see awaitWork)
431     * before blocking (via park). Note the unusual conventions about
432 dl 1.200 * Thread.interrupts surrounding parking and other blocking:
433     * Because interrupts are used solely to alert threads to check
434     * termination, which is checked anyway upon blocking, we clear
435     * status (using Thread.interrupted) before any call to park, so
436     * that park does not immediately return due to status being set
437     * via some other unrelated call to interrupt in user code.
438     *
439     * Signalling and activation. Workers are created or activated
440     * only when there appears to be at least one task they might be
441     * able to find and execute. Upon push (either by a worker or an
442 dl 1.205 * external submission) to a previously (possibly) empty queue,
443     * workers are signalled if idle, or created if fewer exist than
444     * the given parallelism level. These primary signals are
445     * buttressed by others whenever other threads remove a task from
446     * a queue and notice that there are other tasks there as well.
447     * On most platforms, signalling (unpark) overhead time is
448     * noticeably long, and the time between signalling a thread and
449     * it actually making progress can be very noticeably long, so it
450     * is worth offloading these delays from critical paths as much as
451 dl 1.211 * possible. Also, because inactive workers are often rescanning
452 dl 1.200 * or spinning rather than blocking, we set and clear the "parker"
453     * field of WorkQueues to reduce unnecessary calls to unpark.
454     * (This requires a secondary recheck to avoid missed signals.)
455 dl 1.52 *
456     * Trimming workers. To release resources after periods of lack of
457     * use, a worker starting to wait when the pool is quiescent will
458 dl 1.208 * time out and terminate (see awaitWork) if the pool has remained
459     * quiescent for period IDLE_TIMEOUT, increasing the period as the
460     * number of threads decreases, eventually removing all workers.
461     * Also, when more than two spare threads exist, excess threads
462     * are immediately terminated at the next quiescent point.
463 dl 1.211 * (Padding by two avoids hysteresis.)
464 dl 1.52 *
465 dl 1.210 * Shutdown and Termination. A call to shutdownNow invokes
466     * tryTerminate to atomically set a runState bit. The calling
467     * thread, as well as every other worker thereafter terminating,
468     * helps terminate others by setting their (qlock) status,
469     * cancelling their unprocessed tasks, and waking them up, doing
470     * so repeatedly until stable (but with a loop bounded by the
471     * number of workers). Calls to non-abrupt shutdown() preface
472     * this by checking whether termination should commence. This
473     * relies primarily on the active count bits of "ctl" maintaining
474 jsr166 1.212 * consensus -- tryTerminate is called from awaitWork whenever
475 dl 1.211 * quiescent. However, external submitters do not take part in
476     * this consensus. So, tryTerminate sweeps through queues (until
477     * stable) to ensure lack of in-flight submissions and workers
478 dl 1.210 * about to process them before triggering the "STOP" phase of
479 dl 1.211 * termination. (Note: there is an intrinsic conflict if
480     * helpQuiescePool is called when shutdown is enabled. Both wait
481 jsr166 1.212 * for quiescence, but tryTerminate is biased to not trigger until
482 dl 1.211 * helpQuiescePool completes.)
483     *
484 dl 1.78 *
485 jsr166 1.84 * Joining Tasks
486     * =============
487 dl 1.78 *
488     * Any of several actions may be taken when one worker is waiting
489 jsr166 1.84 * to join a task stolen (or always held) by another. Because we
490 dl 1.78 * are multiplexing many tasks on to a pool of workers, we can't
491     * just let them block (as in Thread.join). We also cannot just
492     * reassign the joiner's run-time stack with another and replace
493     * it later, which would be a form of "continuation", that even if
494 dl 1.200 * possible is not necessarily a good idea since we may need both
495     * an unblocked task and its continuation to progress. Instead we
496     * combine two tactics:
497 dl 1.19 *
498     * Helping: Arranging for the joiner to execute some task that it
499 dl 1.78 * would be running if the steal had not occurred.
500 dl 1.19 *
501     * Compensating: Unless there are already enough live threads,
502 dl 1.78 * method tryCompensate() may create or re-activate a spare
503     * thread to compensate for blocked joiners until they unblock.
504     *
505 dl 1.105 * A third form (implemented in tryRemoveAndExec) amounts to
506     * helping a hypothetical compensator: If we can readily tell that
507     * a possible action of a compensator is to steal and execute the
508     * task being joined, the joining thread can do so directly,
509     * without the need for a compensation thread (although at the
510     * expense of larger run-time stacks, but the tradeoff is
511     * typically worthwhile).
512 dl 1.52 *
513     * The ManagedBlocker extension API can't use helping so relies
514     * only on compensation in method awaitBlocker.
515 dl 1.19 *
516 dl 1.200 * The algorithm in helpStealer entails a form of "linear
517     * helping". Each worker records (in field currentSteal) the most
518     * recent task it stole from some other worker (or a submission).
519     * It also records (in field currentJoin) the task it is currently
520     * actively joining. Method helpStealer uses these markers to try
521     * to find a worker to help (i.e., steal back a task from and
522     * execute it) that could hasten completion of the actively joined
523     * task. Thus, the joiner executes a task that would be on its
524     * own local deque had the to-be-joined task not been stolen. This
525     * is a conservative variant of the approach described in Wagner &
526 dl 1.78 * Calder "Leapfrogging: a portable technique for implementing
527     * efficient futures" SIGPLAN Notices, 1993
528     * (http://portal.acm.org/citation.cfm?id=155354). It differs in
529     * that: (1) We only maintain dependency links across workers upon
530     * steals, rather than use per-task bookkeeping. This sometimes
531 dl 1.90 * requires a linear scan of workQueues array to locate stealers,
532     * but often doesn't because stealers leave hints (that may become
533 dl 1.112 * stale/wrong) of where to locate them. It is only a hint
534     * because a worker might have had multiple steals and the hint
535     * records only one of them (usually the most current). Hinting
536     * isolates cost to when it is needed, rather than adding to
537     * per-task overhead. (2) It is "shallow", ignoring nesting and
538     * potentially cyclic mutual steals. (3) It is intentionally
539 dl 1.78 * racy: field currentJoin is updated only while actively joining,
540     * which means that we miss links in the chain during long-lived
541     * tasks, GC stalls etc (which is OK since blocking in such cases
542     * is usually a good idea). (4) We bound the number of attempts
543 dl 1.200 * to find work using checksums and fall back to suspending the
544 dl 1.90 * worker and if necessary replacing it with another.
545 dl 1.78 *
546 dl 1.200 * Helping actions for CountedCompleters do not require tracking
547     * currentJoins: Method helpComplete takes and executes any task
548 jsr166 1.202 * with the same root as the task being waited on (preferring
549     * local pops to non-local polls). However, this still entails
550     * some traversal of completer chains, so is less efficient than
551     * using CountedCompleters without explicit joins.
552 dl 1.105 *
553 dl 1.200 * Compensation does not aim to keep exactly the target
554     * parallelism number of unblocked threads running at any given
555     * time. Some previous versions of this class employed immediate
556     * compensations for any blocked join. However, in practice, the
557     * vast majority of blockages are transient byproducts of GC and
558     * other JVM or OS activities that are made worse by replacement.
559     * Currently, compensation is attempted only after validating that
560     * all purportedly active threads are processing tasks by checking
561     * field WorkQueue.scanState, which eliminates most false
562     * positives. Also, compensation is bypassed (tolerating fewer
563     * threads) in the most common case in which it is rarely
564     * beneficial: when a worker with an empty queue (thus no
565     * continuation tasks) blocks on a join and there still remain
566 dl 1.208 * enough threads to ensure liveness.
567 dl 1.105 *
568 dl 1.211 * The compensation mechanism may be bounded. Bounds for the
569     * commonPool (see commonMaxSpares) better enable JVMs to cope
570 dl 1.208 * with programming errors and abuse before running out of
571     * resources to do so. In other cases, users may supply factories
572     * that limit thread construction. The effects of bounding in this
573     * pool (like all others) is imprecise. Total worker counts are
574     * decremented when threads deregister, not when they exit and
575     * resources are reclaimed by the JVM and OS. So the number of
576     * simultaneously live threads may transiently exceed bounds.
577 dl 1.205 *
578 dl 1.105 * Common Pool
579     * ===========
580     *
581 jsr166 1.175 * The static common pool always exists after static
582 dl 1.105 * initialization. Since it (or any other created pool) need
583     * never be used, we minimize initial construction overhead and
584     * footprint to the setup of about a dozen fields, with no nested
585     * allocation. Most bootstrapping occurs within method
586 dl 1.200 * externalSubmit during the first submission to the pool.
587 dl 1.105 *
588     * When external threads submit to the common pool, they can
589 dl 1.200 * perform subtask processing (see externalHelpComplete and
590     * related methods) upon joins. This caller-helps policy makes it
591     * sensible to set common pool parallelism level to one (or more)
592     * less than the total number of available cores, or even zero for
593     * pure caller-runs. We do not need to record whether external
594     * submissions are to the common pool -- if not, external help
595     * methods return quickly. These submitters would otherwise be
596     * blocked waiting for completion, so the extra effort (with
597     * liberally sprinkled task status checks) in inapplicable cases
598     * amounts to an odd form of limited spin-wait before blocking in
599     * ForkJoinTask.join.
600 dl 1.105 *
601 dl 1.197 * As a more appropriate default in managed environments, unless
602     * overridden by system properties, we use workers of subclass
603     * InnocuousForkJoinWorkerThread when there is a SecurityManager
604     * present. These workers have no permissions set, do not belong
605     * to any user-defined ThreadGroup, and erase all ThreadLocals
606 dl 1.200 * after executing any top-level task (see WorkQueue.runTask).
607     * The associated mechanics (mainly in ForkJoinWorkerThread) may
608     * be JVM-dependent and must access particular Thread class fields
609     * to achieve this effect.
610 jsr166 1.198 *
611 dl 1.105 * Style notes
612     * ===========
613     *
614 dl 1.200 * Memory ordering relies mainly on Unsafe intrinsics that carry
615     * the further responsibility of explicitly performing null- and
616     * bounds- checks otherwise carried out implicitly by JVMs. This
617     * can be awkward and ugly, but also reflects the need to control
618     * outcomes across the unusual cases that arise in very racy code
619     * with very few invariants. So these explicit checks would exist
620     * in some form anyway. All fields are read into locals before
621     * use, and null-checked if they are references. This is usually
622     * done in a "C"-like style of listing declarations at the heads
623     * of methods or blocks, and using inline assignments on first
624     * encounter. Array bounds-checks are usually performed by
625     * masking with array.length-1, which relies on the invariant that
626     * these arrays are created with positive lengths, which is itself
627     * paranoically checked. Nearly all explicit checks lead to
628     * bypass/return, not exception throws, because they may
629     * legitimately arise due to cancellation/revocation during
630     * shutdown.
631     *
632 dl 1.105 * There is a lot of representation-level coupling among classes
633     * ForkJoinPool, ForkJoinWorkerThread, and ForkJoinTask. The
634     * fields of WorkQueue maintain data structures managed by
635     * ForkJoinPool, so are directly accessed. There is little point
636     * trying to reduce this, since any associated future changes in
637     * representations will need to be accompanied by algorithmic
638     * changes anyway. Several methods intrinsically sprawl because
639 dl 1.200 * they must accumulate sets of consistent reads of fields held in
640     * local variables. There are also other coding oddities
641     * (including several unnecessary-looking hoisted null checks)
642     * that help some methods perform reasonably even when interpreted
643     * (not compiled).
644 dl 1.52 *
645 dl 1.208 * The order of declarations in this file is (with a few exceptions):
646 dl 1.86 * (1) Static utility functions
647     * (2) Nested (static) classes
648     * (3) Static fields
649     * (4) Fields, along with constants used when unpacking some of them
650     * (5) Internal control methods
651     * (6) Callbacks and other support for ForkJoinTask methods
652     * (7) Exported methods
653     * (8) Static block initializing statics in minimally dependent order
654     */
655    
656     // Static utilities
657    
658     /**
659     * If there is a security manager, makes sure caller has
660     * permission to modify threads.
661 jsr166 1.1 */
662 dl 1.86 private static void checkPermission() {
663     SecurityManager security = System.getSecurityManager();
664     if (security != null)
665     security.checkPermission(modifyThreadPermission);
666     }
667    
668     // Nested classes
669 jsr166 1.1
670     /**
671 jsr166 1.8 * Factory for creating new {@link ForkJoinWorkerThread}s.
672     * A {@code ForkJoinWorkerThreadFactory} must be defined and used
673     * for {@code ForkJoinWorkerThread} subclasses that extend base
674     * functionality or initialize threads with different contexts.
675 jsr166 1.1 */
676     public static interface ForkJoinWorkerThreadFactory {
677     /**
678     * Returns a new worker thread operating in the given pool.
679     *
680     * @param pool the pool this thread works in
681 jsr166 1.192 * @return the new worker thread
682 jsr166 1.11 * @throws NullPointerException if the pool is null
683 jsr166 1.1 */
684     public ForkJoinWorkerThread newThread(ForkJoinPool pool);
685     }
686    
687     /**
688     * Default ForkJoinWorkerThreadFactory implementation; creates a
689     * new ForkJoinWorkerThread.
690     */
691 dl 1.112 static final class DefaultForkJoinWorkerThreadFactory
692 jsr166 1.1 implements ForkJoinWorkerThreadFactory {
693 dl 1.112 public final ForkJoinWorkerThread newThread(ForkJoinPool pool) {
694 dl 1.14 return new ForkJoinWorkerThread(pool);
695 jsr166 1.1 }
696     }
697    
698     /**
699 dl 1.86 * Class for artificial tasks that are used to replace the target
700     * of local joins if they are removed from an interior queue slot
701     * in WorkQueue.tryRemoveAndExec. We don't need the proxy to
702     * actually do anything beyond having a unique identity.
703 jsr166 1.1 */
704 dl 1.86 static final class EmptyTask extends ForkJoinTask<Void> {
705 dl 1.105 private static final long serialVersionUID = -7721805057305804111L;
706 dl 1.86 EmptyTask() { status = ForkJoinTask.NORMAL; } // force done
707     public final Void getRawResult() { return null; }
708     public final void setRawResult(Void x) {}
709     public final boolean exec() { return true; }
710 jsr166 1.1 }
711    
712 dl 1.200 // Constants shared across ForkJoinPool and WorkQueue
713    
714     // Bounds
715     static final int SMASK = 0xffff; // short bits == max index
716     static final int MAX_CAP = 0x7fff; // max #workers - 1
717     static final int EVENMASK = 0xfffe; // even short bits
718     static final int SQMASK = 0x007e; // max 64 (even) slots
719    
720     // Masks and units for WorkQueue.scanState and ctl sp subfield
721     static final int SCANNING = 1; // false when running tasks
722     static final int INACTIVE = 1 << 31; // must be negative
723 dl 1.211 static final int SS_SEQ = 1 << 16; // version count
724 dl 1.200
725     // Mode bits for ForkJoinPool.config and WorkQueue.config
726 dl 1.211 static final int MODE_MASK = 0xffff << 16; // top half of int
727 dl 1.200 static final int LIFO_QUEUE = 0;
728     static final int FIFO_QUEUE = 1 << 16;
729     static final int SHARED_QUEUE = 1 << 31; // must be negative
730    
731 jsr166 1.1 /**
732 dl 1.78 * Queues supporting work-stealing as well as external task
733 jsr166 1.202 * submission. See above for descriptions and algorithms.
734 dl 1.78 * Performance on most platforms is very sensitive to placement of
735     * instances of both WorkQueues and their arrays -- we absolutely
736     * do not want multiple WorkQueue instances or multiple queue
737 dl 1.200 * arrays sharing cache lines. The @Contended annotation alerts
738     * JVMs to try to keep instances apart.
739 dl 1.78 */
740 jsr166 1.171 @sun.misc.Contended
741 dl 1.78 static final class WorkQueue {
742 dl 1.200
743 dl 1.78 /**
744     * Capacity of work-stealing queue array upon initialization.
745 dl 1.90 * Must be a power of two; at least 4, but should be larger to
746     * reduce or eliminate cacheline sharing among queues.
747     * Currently, it is much larger, as a partial workaround for
748     * the fact that JVMs often place arrays in locations that
749     * share GC bookkeeping (especially cardmarks) such that
750     * per-write accesses encounter serious memory contention.
751 dl 1.78 */
752 dl 1.90 static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
753 dl 1.78
754     /**
755     * Maximum size for queue arrays. Must be a power of two less
756     * than or equal to 1 << (31 - width of array entry) to ensure
757     * lack of wraparound of index calculations, but defined to a
758     * value a bit less than this to help users trap runaway
759     * programs before saturating systems.
760     */
761     static final int MAXIMUM_QUEUE_CAPACITY = 1 << 26; // 64M
762    
763 dl 1.200 // Instance fields
764     volatile int scanState; // versioned, <0: inactive; odd:scanning
765     int stackPred; // pool stack (ctl) predecessor
766 dl 1.178 int nsteals; // number of steals
767 dl 1.200 int hint; // randomization and stealer index hint
768     int config; // pool index and mode
769     volatile int qlock; // 1: locked, < 0: terminate; else 0
770 dl 1.78 volatile int base; // index of next slot for poll
771     int top; // index of next slot for push
772     ForkJoinTask<?>[] array; // the elements (initially unallocated)
773 dl 1.90 final ForkJoinPool pool; // the containing pool (may be null)
774 dl 1.78 final ForkJoinWorkerThread owner; // owning thread or null if shared
775     volatile Thread parker; // == owner during call to park; else null
776 dl 1.95 volatile ForkJoinTask<?> currentJoin; // task being joined in awaitJoin
777 dl 1.200 volatile ForkJoinTask<?> currentSteal; // mainly used by helpStealer
778 dl 1.112
779 dl 1.200 WorkQueue(ForkJoinPool pool, ForkJoinWorkerThread owner) {
780 dl 1.90 this.pool = pool;
781 dl 1.78 this.owner = owner;
782 dl 1.115 // Place indices in the center of array (that is not yet allocated)
783 dl 1.78 base = top = INITIAL_QUEUE_CAPACITY >>> 1;
784     }
785    
786     /**
787 dl 1.200 * Returns an exportable index (used by ForkJoinWorkerThread)
788     */
789     final int getPoolIndex() {
790     return (config & 0xffff) >>> 1; // ignore odd/even tag bit
791     }
792    
793     /**
794 dl 1.115 * Returns the approximate number of tasks in the queue.
795     */
796     final int queueSize() {
797     int n = base - top; // non-owner callers must read base first
798     return (n >= 0) ? 0 : -n; // ignore transient negative
799     }
800    
801 jsr166 1.180 /**
802 dl 1.115 * Provides a more accurate estimate of whether this queue has
803     * any tasks than does queueSize, by checking whether a
804     * near-empty queue has at least one unclaimed task.
805     */
806     final boolean isEmpty() {
807 dl 1.200 ForkJoinTask<?>[] a; int n, m, s;
808     return ((n = base - (s = top)) >= 0 ||
809     (n == -1 && // possibly one task
810     ((a = array) == null || (m = a.length - 1) < 0 ||
811 dl 1.115 U.getObject
812     (a, (long)((m & (s - 1)) << ASHIFT) + ABASE) == null)));
813     }
814    
815     /**
816     * Pushes a task. Call only by owner in unshared queues. (The
817     * shared-queue version is embedded in method externalPush.)
818 dl 1.78 *
819     * @param task the task. Caller must ensure non-null.
820 jsr166 1.146 * @throws RejectedExecutionException if array cannot be resized
821 dl 1.78 */
822 dl 1.90 final void push(ForkJoinTask<?> task) {
823 dl 1.205 ForkJoinTask<?>[] a; ForkJoinPool p;
824     int b = base, s = top, n;
825 dl 1.112 if ((a = array) != null) { // ignore if queue removed
826 dl 1.200 int m = a.length - 1; // fenced write for task visibility
827 dl 1.178 U.putOrderedObject(a, ((m & s) << ASHIFT) + ABASE, task);
828 dl 1.200 U.putOrderedInt(this, QTOP, s + 1);
829 dl 1.205 if ((n = s - b) <= 1) {
830 dl 1.200 if ((p = pool) != null)
831     p.signalWork(p.workQueues, this);
832     }
833 dl 1.211 else if (n >= m)
834 dl 1.112 growArray();
835 dl 1.78 }
836     }
837    
838 dl 1.178 /**
839 dl 1.112 * Initializes or doubles the capacity of array. Call either
840     * by owner or with lock held -- it is OK for base, but not
841     * top, to move while resizings are in progress.
842     */
843     final ForkJoinTask<?>[] growArray() {
844     ForkJoinTask<?>[] oldA = array;
845     int size = oldA != null ? oldA.length << 1 : INITIAL_QUEUE_CAPACITY;
846     if (size > MAXIMUM_QUEUE_CAPACITY)
847     throw new RejectedExecutionException("Queue capacity exceeded");
848     int oldMask, t, b;
849     ForkJoinTask<?>[] a = array = new ForkJoinTask<?>[size];
850     if (oldA != null && (oldMask = oldA.length - 1) >= 0 &&
851     (t = top) - (b = base) > 0) {
852     int mask = size - 1;
853 dl 1.200 do { // emulate poll from old array, push to new array
854 dl 1.112 ForkJoinTask<?> x;
855     int oldj = ((b & oldMask) << ASHIFT) + ABASE;
856     int j = ((b & mask) << ASHIFT) + ABASE;
857     x = (ForkJoinTask<?>)U.getObjectVolatile(oldA, oldj);
858     if (x != null &&
859     U.compareAndSwapObject(oldA, oldj, x, null))
860     U.putObjectVolatile(a, j, x);
861     } while (++b != t);
862 dl 1.78 }
863 dl 1.112 return a;
864 dl 1.78 }
865    
866     /**
867 dl 1.90 * Takes next task, if one exists, in LIFO order. Call only
868 dl 1.102 * by owner in unshared queues.
869 dl 1.90 */
870     final ForkJoinTask<?> pop() {
871 dl 1.94 ForkJoinTask<?>[] a; ForkJoinTask<?> t; int m;
872     if ((a = array) != null && (m = a.length - 1) >= 0) {
873 dl 1.90 for (int s; (s = top - 1) - base >= 0;) {
874 dl 1.94 long j = ((m & s) << ASHIFT) + ABASE;
875     if ((t = (ForkJoinTask<?>)U.getObject(a, j)) == null)
876 dl 1.90 break;
877     if (U.compareAndSwapObject(a, j, t, null)) {
878 dl 1.200 U.putOrderedInt(this, QTOP, s);
879 dl 1.90 return t;
880     }
881     }
882     }
883     return null;
884     }
885    
886     /**
887     * Takes a task in FIFO order if b is base of queue and a task
888     * can be claimed without contention. Specialized versions
889 dl 1.200 * appear in ForkJoinPool methods scan and helpStealer.
890 dl 1.78 */
891 dl 1.90 final ForkJoinTask<?> pollAt(int b) {
892 dl 1.178 ForkJoinTask<?> t; ForkJoinTask<?>[] a;
893 dl 1.90 if ((a = array) != null) {
894 dl 1.86 int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
895     if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) != null &&
896 dl 1.178 base == b && U.compareAndSwapObject(a, j, t, null)) {
897 dl 1.200 base = b + 1;
898 dl 1.78 return t;
899     }
900     }
901     return null;
902     }
903    
904     /**
905 dl 1.90 * Takes next task, if one exists, in FIFO order.
906 dl 1.78 */
907 dl 1.90 final ForkJoinTask<?> poll() {
908 dl 1.178 ForkJoinTask<?>[] a; int b; ForkJoinTask<?> t;
909 dl 1.90 while ((b = base) - top < 0 && (a = array) != null) {
910     int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
911     t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
912 dl 1.200 if (base == b) {
913     if (t != null) {
914     if (U.compareAndSwapObject(a, j, t, null)) {
915     base = b + 1;
916     return t;
917     }
918 dl 1.78 }
919 dl 1.200 else if (b + 1 == top) // now empty
920 dl 1.90 break;
921     }
922 dl 1.78 }
923     return null;
924     }
925    
926     /**
927     * Takes next task, if one exists, in order specified by mode.
928     */
929     final ForkJoinTask<?> nextLocalTask() {
930 dl 1.200 return (config & FIFO_QUEUE) == 0 ? pop() : poll();
931 dl 1.78 }
932    
933     /**
934     * Returns next task, if one exists, in order specified by mode.
935     */
936     final ForkJoinTask<?> peek() {
937     ForkJoinTask<?>[] a = array; int m;
938     if (a == null || (m = a.length - 1) < 0)
939     return null;
940 dl 1.200 int i = (config & FIFO_QUEUE) == 0 ? top - 1 : base;
941 dl 1.78 int j = ((i & m) << ASHIFT) + ABASE;
942     return (ForkJoinTask<?>)U.getObjectVolatile(a, j);
943     }
944    
945     /**
946     * Pops the given task only if it is at the current top.
947 dl 1.105 * (A shared version is available only via FJP.tryExternalUnpush)
948 dl 1.200 */
949 dl 1.78 final boolean tryUnpush(ForkJoinTask<?> t) {
950     ForkJoinTask<?>[] a; int s;
951     if ((a = array) != null && (s = top) != base &&
952     U.compareAndSwapObject
953     (a, (((a.length - 1) & --s) << ASHIFT) + ABASE, t, null)) {
954 dl 1.200 U.putOrderedInt(this, QTOP, s);
955 dl 1.78 return true;
956     }
957     return false;
958     }
959    
960     /**
961 jsr166 1.84 * Removes and cancels all known tasks, ignoring any exceptions.
962 dl 1.78 */
963     final void cancelAll() {
964 dl 1.200 ForkJoinTask<?> t;
965     if ((t = currentJoin) != null) {
966     currentJoin = null;
967     ForkJoinTask.cancelIgnoringExceptions(t);
968     }
969     if ((t = currentSteal) != null) {
970     currentSteal = null;
971     ForkJoinTask.cancelIgnoringExceptions(t);
972     }
973     while ((t = poll()) != null)
974 dl 1.78 ForkJoinTask.cancelIgnoringExceptions(t);
975     }
976    
977 dl 1.104 // Specialized execution methods
978 dl 1.78
979     /**
980 dl 1.178 * Polls and runs tasks until empty.
981 dl 1.78 */
982 dl 1.178 final void pollAndExecAll() {
983     for (ForkJoinTask<?> t; (t = poll()) != null;)
984     t.doExec();
985 dl 1.94 }
986    
987     /**
988 dl 1.200 * Removes and executes all local tasks. If LIFO, invokes
989     * pollAndExecAll. Otherwise implements a specialized pop loop
990     * to exec until empty.
991     */
992     final void execLocalTasks() {
993     int b = base, m, s;
994     ForkJoinTask<?>[] a = array;
995     if (b - (s = top - 1) <= 0 && a != null &&
996     (m = a.length - 1) >= 0) {
997     if ((config & FIFO_QUEUE) == 0) {
998     for (ForkJoinTask<?> t;;) {
999     if ((t = (ForkJoinTask<?>)U.getAndSetObject
1000     (a, ((m & s) << ASHIFT) + ABASE, null)) == null)
1001     break;
1002     U.putOrderedInt(this, QTOP, s);
1003     t.doExec();
1004     if (base - (s = top - 1) > 0)
1005     break;
1006     }
1007     }
1008     else
1009     pollAndExecAll();
1010     }
1011     }
1012    
1013     /**
1014     * Executes the given task and any remaining local tasks
1015 dl 1.94 */
1016 dl 1.178 final void runTask(ForkJoinTask<?> task) {
1017 dl 1.200 if (task != null) {
1018     scanState &= ~SCANNING; // mark as busy
1019     (currentSteal = task).doExec();
1020     U.putOrderedObject(this, QCURRENTSTEAL, null); // release for GC
1021     execLocalTasks();
1022     ForkJoinWorkerThread thread = owner;
1023 dl 1.178 ++nsteals;
1024 dl 1.200 scanState |= SCANNING;
1025     if (thread != null)
1026 dl 1.197 thread.afterTopLevelExec();
1027 dl 1.178 }
1028 dl 1.94 }
1029    
1030     /**
1031 dl 1.105 * If present, removes from queue and executes the given task,
1032 dl 1.200 * or any other cancelled task. Used only by awaitJoin
1033 dl 1.94 *
1034 dl 1.200 * Returns true if queue empty and task not known to be done
1035 dl 1.94 */
1036 dl 1.105 final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
1037 dl 1.94 ForkJoinTask<?>[] a; int m, s, b, n;
1038 dl 1.200 if ((a = array) != null && (m = a.length - 1) >= 0 &&
1039     task != null) {
1040     while ((n = (s = top) - (b = base)) > 0) {
1041     for (ForkJoinTask<?> t;;) { // traverse from s to b
1042     long j = ((--s & m) << ASHIFT) + ABASE;
1043     if ((t = (ForkJoinTask<?>)U.getObject(a, j)) == null)
1044     return s + 1 == top; // shorter than expected
1045     else if (t == task) {
1046     boolean removed = false;
1047     if (s + 1 == top) { // pop
1048     if (U.compareAndSwapObject(a, j, task, null)) {
1049     U.putOrderedInt(this, QTOP, s);
1050     removed = true;
1051     }
1052     }
1053     else if (base == b) // replace with proxy
1054     removed = U.compareAndSwapObject(
1055     a, j, task, new EmptyTask());
1056     if (removed)
1057     task.doExec();
1058     break;
1059 dl 1.90 }
1060 dl 1.200 else if (t.status < 0 && s + 1 == top) {
1061     if (U.compareAndSwapObject(a, j, t, null))
1062     U.putOrderedInt(this, QTOP, s);
1063     break; // was cancelled
1064 dl 1.104 }
1065 dl 1.200 if (--n == 0)
1066     return false;
1067 dl 1.104 }
1068 dl 1.200 if (task.status < 0)
1069     return false;
1070 dl 1.104 }
1071     }
1072 dl 1.200 return true;
1073 dl 1.104 }
1074    
1075     /**
1076 dl 1.200 * Pops task if in the same CC computation as the given task,
1077     * in either shared or owned mode. Used only by helpComplete.
1078 dl 1.78 */
1079 dl 1.200 final CountedCompleter<?> popCC(CountedCompleter<?> task, int mode) {
1080     int s; ForkJoinTask<?>[] a; Object o;
1081 dl 1.178 if (base - (s = top) < 0 && (a = array) != null) {
1082     long j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE;
1083 dl 1.200 if ((o = U.getObjectVolatile(a, j)) != null &&
1084     (o instanceof CountedCompleter)) {
1085     CountedCompleter<?> t = (CountedCompleter<?>)o;
1086     for (CountedCompleter<?> r = t;;) {
1087     if (r == task) {
1088     if (mode < 0) { // must lock
1089     if (U.compareAndSwapInt(this, QLOCK, 0, 1)) {
1090     if (top == s && array == a &&
1091     U.compareAndSwapObject(a, j, t, null)) {
1092     U.putOrderedInt(this, QTOP, s - 1);
1093     U.putOrderedInt(this, QLOCK, 0);
1094     return t;
1095     }
1096 dl 1.209 U.compareAndSwapInt(this, QLOCK, 1, 0);
1097 dl 1.178 }
1098     }
1099 dl 1.200 else if (U.compareAndSwapObject(a, j, t, null)) {
1100     U.putOrderedInt(this, QTOP, s - 1);
1101     return t;
1102     }
1103     break;
1104 dl 1.178 }
1105 dl 1.200 else if ((r = r.completer) == null) // try parent
1106 dl 1.178 break;
1107     }
1108 dl 1.94 }
1109 dl 1.78 }
1110 dl 1.200 return null;
1111 dl 1.78 }
1112    
1113     /**
1114 dl 1.200 * Steals and runs a task in the same CC computation as the
1115     * given task if one exists and can be taken without
1116     * contention. Otherwise returns a checksum/control value for
1117     * use by method helpComplete.
1118     *
1119     * @return 1 if successful, 2 if retryable (lost to another
1120     * stealer), -1 if non-empty but no matching task found, else
1121     * the base index, forced negative.
1122     */
1123     final int pollAndExecCC(CountedCompleter<?> task) {
1124     int b, h; ForkJoinTask<?>[] a; Object o;
1125     if ((b = base) - top >= 0 || (a = array) == null)
1126     h = b | Integer.MIN_VALUE; // to sense movement on re-poll
1127     else {
1128     long j = (((a.length - 1) & b) << ASHIFT) + ABASE;
1129     if ((o = U.getObjectVolatile(a, j)) == null)
1130     h = 2; // retryable
1131     else if (!(o instanceof CountedCompleter))
1132     h = -1; // unmatchable
1133     else {
1134     CountedCompleter<?> t = (CountedCompleter<?>)o;
1135     for (CountedCompleter<?> r = t;;) {
1136     if (r == task) {
1137     if (base == b &&
1138     U.compareAndSwapObject(a, j, t, null)) {
1139     base = b + 1;
1140 dl 1.178 t.doExec();
1141 dl 1.200 h = 1; // success
1142 dl 1.178 }
1143 dl 1.200 else
1144     h = 2; // lost CAS
1145     break;
1146 dl 1.178 }
1147 dl 1.200 else if ((r = r.completer) == null) {
1148     h = -1; // unmatched
1149 dl 1.178 break;
1150 dl 1.200 }
1151 dl 1.178 }
1152     }
1153 dl 1.78 }
1154 dl 1.200 return h;
1155 dl 1.78 }
1156    
1157     /**
1158 dl 1.86 * Returns true if owned and not known to be blocked.
1159     */
1160     final boolean isApparentlyUnblocked() {
1161     Thread wt; Thread.State s;
1162 dl 1.200 return (scanState >= 0 &&
1163 dl 1.86 (wt = owner) != null &&
1164     (s = wt.getState()) != Thread.State.BLOCKED &&
1165     s != Thread.State.WAITING &&
1166     s != Thread.State.TIMED_WAITING);
1167     }
1168    
1169 dl 1.211 // Unsafe mechanics. Note that some are (and must be) the same as in FJP
1170 dl 1.78 private static final sun.misc.Unsafe U;
1171 dl 1.200 private static final int ABASE;
1172     private static final int ASHIFT;
1173 dl 1.170 private static final long QBASE;
1174 dl 1.200 private static final long QTOP;
1175 dl 1.105 private static final long QLOCK;
1176 dl 1.200 private static final long QSCANSTATE;
1177     private static final long QCURRENTSTEAL;
1178 dl 1.78 static {
1179     try {
1180     U = sun.misc.Unsafe.getUnsafe();
1181 dl 1.200 Class<?> wk = WorkQueue.class;
1182 dl 1.78 Class<?> ak = ForkJoinTask[].class;
1183 dl 1.170 QBASE = U.objectFieldOffset
1184 dl 1.200 (wk.getDeclaredField("base"));
1185     QTOP = U.objectFieldOffset
1186     (wk.getDeclaredField("top"));
1187 dl 1.105 QLOCK = U.objectFieldOffset
1188 dl 1.200 (wk.getDeclaredField("qlock"));
1189     QSCANSTATE = U.objectFieldOffset
1190     (wk.getDeclaredField("scanState"));
1191     QCURRENTSTEAL = U.objectFieldOffset
1192     (wk.getDeclaredField("currentSteal"));
1193 dl 1.78 ABASE = U.arrayBaseOffset(ak);
1194 jsr166 1.142 int scale = U.arrayIndexScale(ak);
1195     if ((scale & (scale - 1)) != 0)
1196     throw new Error("data type scale not a power of two");
1197     ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
1198 dl 1.78 } catch (Exception e) {
1199     throw new Error(e);
1200     }
1201     }
1202     }
1203 dl 1.14
1204 dl 1.112 // static fields (initialized in static initializer below)
1205    
1206     /**
1207     * Creates a new ForkJoinWorkerThread. This factory is used unless
1208     * overridden in ForkJoinPool constructors.
1209     */
1210     public static final ForkJoinWorkerThreadFactory
1211     defaultForkJoinWorkerThreadFactory;
1212    
1213 jsr166 1.1 /**
1214 dl 1.115 * Permission required for callers of methods that may start or
1215     * kill threads.
1216     */
1217     private static final RuntimePermission modifyThreadPermission;
1218    
1219     /**
1220 dl 1.101 * Common (static) pool. Non-null for public use unless a static
1221 dl 1.105 * construction exception, but internal usages null-check on use
1222     * to paranoically avoid potential initialization circularities
1223     * as well as to simplify generated code.
1224 dl 1.101 */
1225 dl 1.134 static final ForkJoinPool common;
1226 dl 1.101
1227     /**
1228 dl 1.160 * Common pool parallelism. To allow simpler use and management
1229     * when common pool threads are disabled, we allow the underlying
1230 dl 1.185 * common.parallelism field to be zero, but in that case still report
1231 dl 1.160 * parallelism as 1 to reflect resulting caller-runs mechanics.
1232 dl 1.90 */
1233 dl 1.134 static final int commonParallelism;
1234 dl 1.90
1235     /**
1236 dl 1.208 * Limit on spare thread construction in tryCompensate.
1237     */
1238     private static int commonMaxSpares;
1239    
1240     /**
1241 dl 1.105 * Sequence number for creating workerNamePrefix.
1242 dl 1.86 */
1243 dl 1.105 private static int poolNumberSequence;
1244 dl 1.86
1245 jsr166 1.1 /**
1246 jsr166 1.132 * Returns the next sequence number. We don't expect this to
1247     * ever contend, so use simple builtin sync.
1248 dl 1.83 */
1249 dl 1.105 private static final synchronized int nextPoolId() {
1250     return ++poolNumberSequence;
1251     }
1252 dl 1.86
1253 dl 1.200 // static configuration constants
1254 dl 1.86
1255     /**
1256 dl 1.105 * Initial timeout value (in nanoseconds) for the thread
1257     * triggering quiescence to park waiting for new work. On timeout,
1258     * the thread will instead try to shrink the number of
1259     * workers. The value should be large enough to avoid overly
1260     * aggressive shrinkage during most transient stalls (long GCs
1261     * etc).
1262 dl 1.86 */
1263 dl 1.208 private static final long IDLE_TIMEOUT = 2000L * 1000L * 1000L; // 2sec
1264 dl 1.86
1265     /**
1266 dl 1.120 * Tolerance for idle timeouts, to cope with timer undershoots
1267     */
1268 dl 1.208 private static final long TIMEOUT_SLOP = 20L * 1000L * 1000L; // 20ms
1269 dl 1.200
1270     /**
1271 dl 1.208 * The initial value for commonMaxSpares during static
1272     * initialization unless overridden using System property
1273     * "java.util.concurrent.ForkJoinPool.common.maximumSpares". The
1274     * default value is far in excess of normal requirements, but also
1275 dl 1.200 * far short of MAX_CAP and typical OS thread limits, so allows
1276     * JVMs to catch misuse/abuse before running out of resources
1277     * needed to do so.
1278     */
1279 dl 1.208 private static final int DEFAULT_COMMON_MAX_SPARES = 256;
1280 dl 1.120
1281     /**
1282 dl 1.200 * Number of times to spin-wait before blocking. The spins (in
1283     * awaitRunStateLock and awaitWork) currently use randomized
1284     * spins. If/when MWAIT-like intrinsics becomes available, they
1285     * may allow quieter spinning. The value of SPINS must be a power
1286     * of two, at least 4. The current value causes spinning for a
1287 dl 1.211 * small fraction of typical context-switch times, well worthwhile
1288     * given the typical likelihoods that blocking is not necessary.
1289 dl 1.90 */
1290 dl 1.200 private static final int SPINS = 1 << 11;
1291 dl 1.90
1292     /**
1293     * Increment for seed generators. See class ThreadLocal for
1294     * explanation.
1295     */
1296 dl 1.193 private static final int SEED_INCREMENT = 0x9e3779b9;
1297 dl 1.83
1298 jsr166 1.163 /*
1299 dl 1.200 * Bits and masks for field ctl, packed with 4 16 bit subfields:
1300     * AC: Number of active running workers minus target parallelism
1301     * TC: Number of total workers minus target parallelism
1302     * SS: version count and status of top waiting thread
1303     * ID: poolIndex of top of Treiber stack of waiters
1304     *
1305     * When convenient, we can extract the lower 32 stack top bits
1306     * (including version bits) as sp=(int)ctl. The offsets of counts
1307     * by the target parallelism and the positionings of fields makes
1308     * it possible to perform the most common checks via sign tests of
1309     * fields: When ac is negative, there are not enough active
1310     * workers, when tc is negative, there are not enough total
1311     * workers. When sp is non-zero, there are waiting workers. To
1312     * deal with possibly negative fields, we use casts in and out of
1313     * "short" and/or signed shifts to maintain signedness.
1314     *
1315     * Because it occupies uppermost bits, we can add one active count
1316     * using getAndAddLong of AC_UNIT, rather than CAS, when returning
1317     * from a blocked join. Other updates entail multiple subfields
1318     * and masking, requiring CAS.
1319     */
1320    
1321     // Lower and upper word masks
1322     private static final long SP_MASK = 0xffffffffL;
1323     private static final long UC_MASK = ~SP_MASK;
1324 dl 1.86
1325 dl 1.200 // Active counts
1326 dl 1.86 private static final int AC_SHIFT = 48;
1327 dl 1.200 private static final long AC_UNIT = 0x0001L << AC_SHIFT;
1328     private static final long AC_MASK = 0xffffL << AC_SHIFT;
1329    
1330     // Total counts
1331 dl 1.86 private static final int TC_SHIFT = 32;
1332 dl 1.200 private static final long TC_UNIT = 0x0001L << TC_SHIFT;
1333     private static final long TC_MASK = 0xffffL << TC_SHIFT;
1334     private static final long ADD_WORKER = 0x0001L << (TC_SHIFT + 15); // sign
1335    
1336 dl 1.205 // runState bits: SHUTDOWN must be negative, others arbitrary powers of two
1337 dl 1.200 private static final int RSLOCK = 1;
1338     private static final int RSIGNAL = 1 << 1;
1339     private static final int STARTED = 1 << 2;
1340 dl 1.205 private static final int STOP = 1 << 29;
1341     private static final int TERMINATED = 1 << 30;
1342     private static final int SHUTDOWN = 1 << 31;
1343 dl 1.86
1344     // Instance fields
1345 dl 1.200 volatile long stealCount; // collects worker counts
1346     volatile long ctl; // main pool control
1347     volatile int runState; // lockable status
1348     final int config; // parallelism, mode
1349     int indexSeed; // to generate worker index
1350     volatile WorkQueue[] workQueues; // main registry
1351 dl 1.112 final ForkJoinWorkerThreadFactory factory;
1352 dl 1.200 final UncaughtExceptionHandler ueh; // per-worker UEH
1353     final String workerNamePrefix; // to create worker name string
1354 dl 1.101
1355 jsr166 1.145 /**
1356 dl 1.200 * Acquires the runState lock; returns current (locked) runState
1357 dl 1.105 */
1358 dl 1.200 private int lockRunState() {
1359     int rs;
1360     return ((((rs = runState) & RSLOCK) != 0 ||
1361     !U.compareAndSwapInt(this, RUNSTATE, rs, rs |= RSLOCK)) ?
1362     awaitRunStateLock() : rs);
1363     }
1364    
1365     /**
1366     * Spins and/or blocks until runstate lock is available. This
1367     * method is called only if an initial CAS fails. This acts as a
1368     * spinlock for normal cases, but falls back to builtin monitor to
1369     * block when (rarely) needed. This would be a terrible idea for a
1370     * highly contended lock, but most pools run without the lock ever
1371     * contending after the spin limit, so this works fine as a more
1372     * conservative alternative to a pure spinlock.
1373     */
1374     private int awaitRunStateLock() {
1375 dl 1.210 boolean wasInterrupted = false;
1376     for (int spins = SPINS, r = 0, rs, ns;;) {
1377 dl 1.200 if (((rs = runState) & RSLOCK) == 0) {
1378 dl 1.210 if (U.compareAndSwapInt(this, RUNSTATE, rs, ns = rs | RSLOCK)) {
1379     if (wasInterrupted) {
1380     try {
1381     Thread.currentThread().interrupt();
1382     } catch (SecurityException ignore) {
1383     }
1384     }
1385     return ns;
1386     }
1387 dl 1.200 }
1388     else if (r == 0)
1389     r = ThreadLocalRandom.nextSecondarySeed();
1390     else if (spins > 0) {
1391     r ^= r << 6; r ^= r >>> 21; r ^= r << 7; // xorshift
1392     if (r >= 0)
1393 dl 1.101 --spins;
1394     }
1395 dl 1.200 else if (U.compareAndSwapInt(this, RUNSTATE, rs, rs | RSIGNAL)) {
1396 jsr166 1.106 synchronized (this) {
1397 dl 1.200 if ((runState & RSIGNAL) != 0) {
1398 dl 1.101 try {
1399     wait();
1400     } catch (InterruptedException ie) {
1401 dl 1.210 if (!(Thread.currentThread() instanceof
1402     ForkJoinWorkerThread))
1403     wasInterrupted = true;
1404 dl 1.101 }
1405     }
1406     else
1407 dl 1.105 notifyAll();
1408 dl 1.101 }
1409     }
1410     }
1411     }
1412 dl 1.78
1413 jsr166 1.1 /**
1414 dl 1.200 * Unlocks and sets runState to newRunState.
1415     *
1416     * @param oldRunState a value returned from lockRunState
1417     * @param newRunState the next value (must have lock bit clear).
1418 jsr166 1.1 */
1419 dl 1.200 private void unlockRunState(int oldRunState, int newRunState) {
1420     if (!U.compareAndSwapInt(this, RUNSTATE, oldRunState, newRunState)) {
1421     runState = newRunState; // clears RSIGNAL bit
1422     synchronized (this) { notifyAll(); }
1423     }
1424 dl 1.78 }
1425 jsr166 1.1
1426 dl 1.200 // Creating, registering and deregistering workers
1427    
1428 dl 1.112 /**
1429 dl 1.200 * Tries to construct and start one worker. Assumes that total
1430     * count has already been incremented as a reservation. Invokes
1431     * deregisterWorker on any failure.
1432     *
1433     * @return true if successful
1434 dl 1.115 */
1435 dl 1.200 private boolean createWorker() {
1436     ForkJoinWorkerThreadFactory fac = factory;
1437     Throwable ex = null;
1438     ForkJoinWorkerThread wt = null;
1439     try {
1440     if (fac != null && (wt = fac.newThread(this)) != null) {
1441     wt.start();
1442     return true;
1443 dl 1.115 }
1444 dl 1.200 } catch (Throwable rex) {
1445     ex = rex;
1446 dl 1.112 }
1447 dl 1.200 deregisterWorker(wt, ex);
1448     return false;
1449 dl 1.112 }
1450    
1451 dl 1.200 /**
1452     * Tries to add one worker, incrementing ctl counts before doing
1453     * so, relying on createWorker to back out on failure.
1454     *
1455     * @param c incoming ctl value, with total count negative and no
1456     * idle workers. On CAS failure, c is refreshed and retried if
1457 jsr166 1.202 * this holds (otherwise, a new worker is not needed).
1458 dl 1.200 */
1459     private void tryAddWorker(long c) {
1460     boolean add = false;
1461     do {
1462     long nc = ((AC_MASK & (c + AC_UNIT)) |
1463     (TC_MASK & (c + TC_UNIT)));
1464     if (ctl == c) {
1465     int rs, stop; // check if terminating
1466     if ((stop = (rs = lockRunState()) & STOP) == 0)
1467     add = U.compareAndSwapLong(this, CTL, c, nc);
1468     unlockRunState(rs, rs & ~RSLOCK);
1469     if (stop != 0)
1470     break;
1471     if (add) {
1472     createWorker();
1473     break;
1474     }
1475     }
1476     } while (((c = ctl) & ADD_WORKER) != 0L && (int)c == 0);
1477     }
1478 dl 1.112
1479     /**
1480 dl 1.200 * Callback from ForkJoinWorkerThread constructor to establish and
1481     * record its WorkQueue.
1482 dl 1.112 *
1483     * @param wt the worker thread
1484 dl 1.115 * @return the worker's queue
1485 dl 1.112 */
1486 dl 1.115 final WorkQueue registerWorker(ForkJoinWorkerThread wt) {
1487 dl 1.200 UncaughtExceptionHandler handler;
1488     wt.setDaemon(true); // configure thread
1489 dl 1.115 if ((handler = ueh) != null)
1490     wt.setUncaughtExceptionHandler(handler);
1491 dl 1.200 WorkQueue w = new WorkQueue(this, wt);
1492     int i = 0; // assign a pool index
1493     int mode = config & MODE_MASK;
1494     int rs = lockRunState();
1495 dl 1.115 try {
1496 dl 1.200 WorkQueue[] ws; int n; // skip if no array
1497     if ((ws = workQueues) != null && (n = ws.length) > 0) {
1498     int s = indexSeed += SEED_INCREMENT; // unlikely to collide
1499     int m = n - 1;
1500     i = ((s << 1) | 1) & m; // odd-numbered indices
1501     if (ws[i] != null) { // collision
1502     int probes = 0; // step by approx half n
1503 dl 1.115 int step = (n <= 4) ? 2 : ((n >>> 1) & EVENMASK) + 2;
1504 dl 1.200 while (ws[i = (i + step) & m] != null) {
1505 dl 1.115 if (++probes >= n) {
1506     workQueues = ws = Arrays.copyOf(ws, n <<= 1);
1507     m = n - 1;
1508     probes = 0;
1509 dl 1.94 }
1510     }
1511     }
1512 dl 1.200 w.hint = s; // use as random seed
1513     w.config = i | mode;
1514     w.scanState = i; // publication fence
1515     ws[i] = w;
1516 dl 1.78 }
1517 dl 1.115 } finally {
1518 dl 1.200 unlockRunState(rs, rs & ~RSLOCK);
1519 dl 1.78 }
1520 dl 1.200 wt.setName(workerNamePrefix.concat(Integer.toString(i >>> 1)));
1521 dl 1.115 return w;
1522 dl 1.78 }
1523 dl 1.19
1524 jsr166 1.1 /**
1525 dl 1.86 * Final callback from terminating worker, as well as upon failure
1526 dl 1.105 * to construct or start a worker. Removes record of worker from
1527     * array, and adjusts counts. If pool is shutting down, tries to
1528     * complete termination.
1529 dl 1.78 *
1530 jsr166 1.151 * @param wt the worker thread, or null if construction failed
1531 dl 1.78 * @param ex the exception causing failure, or null if none
1532 dl 1.45 */
1533 dl 1.78 final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1534     WorkQueue w = null;
1535     if (wt != null && (w = wt.workQueue) != null) {
1536 dl 1.200 WorkQueue[] ws; // remove index from array
1537     int idx = w.config & SMASK;
1538     int rs = lockRunState();
1539     if ((ws = workQueues) != null && ws.length > idx && ws[idx] == w)
1540     ws[idx] = null;
1541     unlockRunState(rs, rs & ~RSLOCK);
1542     }
1543     long c; // decrement counts
1544     do {} while (!U.compareAndSwapLong
1545     (this, CTL, c = ctl, ((AC_MASK & (c - AC_UNIT)) |
1546     (TC_MASK & (c - TC_UNIT)) |
1547     (SP_MASK & c))));
1548     if (w != null) {
1549     w.qlock = -1; // ensure set
1550     w.cancelAll(); // cancel remaining tasks
1551 dl 1.178 U.getAndAddLong(this, STEALCOUNT, w.nsteals); // collect steals
1552 dl 1.78 }
1553 dl 1.209 for (;;) { // possibly replace
1554 dl 1.205 WorkQueue[] ws; int m, sp;
1555 dl 1.209 if (tryTerminate(false, false) || w == null || w.array == null ||
1556     (runState & STOP) != 0 || (ws = workQueues) == null ||
1557     (m = ws.length - 1) < 0) // already terminating
1558     break;
1559     if ((sp = (int)(c = ctl)) != 0) { // wake up replacement
1560     if (tryRelease(c, ws[sp & m], AC_UNIT))
1561 dl 1.205 break;
1562 dl 1.120 }
1563 dl 1.209 else if (ex != null && (c & ADD_WORKER) != 0L) {
1564     tryAddWorker(c); // create replacement
1565     break;
1566     }
1567     else // don't need replacement
1568     break;
1569 dl 1.78 }
1570 dl 1.200 if (ex == null) // help clean on way out
1571 dl 1.120 ForkJoinTask.helpExpungeStaleExceptions();
1572 dl 1.200 else // rethrow
1573 dl 1.104 ForkJoinTask.rethrow(ex);
1574 dl 1.78 }
1575 dl 1.52
1576 dl 1.200 // Signalling
1577 dl 1.19
1578     /**
1579 dl 1.115 * Tries to create or activate a worker if too few are active.
1580     *
1581 dl 1.178 * @param ws the worker array to use to find signallees
1582 dl 1.200 * @param q a WorkQueue --if non-null, don't retry if now empty
1583 dl 1.105 */
1584 dl 1.178 final void signalWork(WorkQueue[] ws, WorkQueue q) {
1585 dl 1.200 long c; int sp, i; WorkQueue v; Thread p;
1586 dl 1.211 while ((c = ctl) < 0L) { // too few active
1587 dl 1.200 if ((sp = (int)c) == 0) { // no idle workers
1588     if ((c & ADD_WORKER) != 0L) // too few workers
1589     tryAddWorker(c);
1590     break;
1591     }
1592     if (ws == null) // unstarted/terminated
1593 dl 1.174 break;
1594 dl 1.200 if (ws.length <= (i = sp & SMASK)) // terminated
1595 dl 1.115 break;
1596 dl 1.200 if ((v = ws[i]) == null) // terminating
1597 dl 1.174 break;
1598 dl 1.200 int vs = (sp + SS_SEQ) & ~INACTIVE; // next scanState
1599     int d = sp - v.scanState; // screen CAS
1600     long nc = (UC_MASK & (c + AC_UNIT)) | (SP_MASK & v.stackPred);
1601     if (d == 0 && U.compareAndSwapLong(this, CTL, c, nc)) {
1602     v.scanState = vs; // activate v
1603     if ((p = v.parker) != null)
1604 dl 1.174 U.unpark(p);
1605     break;
1606     }
1607 dl 1.205 if (q != null && q.base == q.top) // no more work
1608 dl 1.174 break;
1609 dl 1.52 }
1610 dl 1.14 }
1611    
1612 dl 1.200 /**
1613     * Signals and releases worker v if it is top of idle worker
1614     * stack. This performs a one-shot version of signalWork only if
1615     * there is (apparently) at least one idle worker.
1616     *
1617     * @param c incoming ctl value
1618     * @param v if non-null, a worker
1619     * @param inc the increment to active count (zero when compensating)
1620     * @return true if successful
1621     */
1622     private boolean tryRelease(long c, WorkQueue v, long inc) {
1623     int sp = (int)c, vs = (sp + SS_SEQ) & ~INACTIVE; Thread p;
1624 dl 1.211 if (v != null && v.scanState == sp) { // v is at top of stack
1625 dl 1.200 long nc = (UC_MASK & (c + inc)) | (SP_MASK & v.stackPred);
1626     if (U.compareAndSwapLong(this, CTL, c, nc)) {
1627     v.scanState = vs;
1628     if ((p = v.parker) != null)
1629     U.unpark(p);
1630     return true;
1631     }
1632     }
1633     return false;
1634     }
1635    
1636 dl 1.90 // Scanning for tasks
1637    
1638 dl 1.14 /**
1639 dl 1.90 * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1640 dl 1.14 */
1641 dl 1.90 final void runWorker(WorkQueue w) {
1642 dl 1.200 w.growArray(); // allocate queue
1643     int seed = w.hint; // initially holds randomization hint
1644     int r = (seed == 0) ? 1 : seed; // avoid 0 for xorShift
1645     for (ForkJoinTask<?> t;;) {
1646     if ((t = scan(w, r)) != null)
1647     w.runTask(t);
1648     else if (!awaitWork(w, r))
1649     break;
1650 dl 1.178 r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
1651     }
1652 dl 1.14 }
1653    
1654     /**
1655 dl 1.200 * Scans for and tries to steal a top-level task. Scans start at a
1656 jsr166 1.202 * random location, randomly moving on apparent contention,
1657 dl 1.200 * otherwise continuing linearly until reaching two consecutive
1658     * empty passes over all queues with the same checksum (summing
1659     * each base index of each queue, that moves on each steal), at
1660     * which point the worker tries to inactivate and then re-scans,
1661     * attempting to re-activate (itself or some other worker) if
1662     * finding a task; otherwise returning null to await work. Scans
1663     * otherwise touch as little memory as possible, to reduce
1664     * disruption on other scanning threads.
1665 dl 1.78 *
1666     * @param w the worker (via its WorkQueue)
1667 dl 1.178 * @param r a random seed
1668 dl 1.200 * @return a task, or null if none found
1669 dl 1.78 */
1670 dl 1.200 private ForkJoinTask<?> scan(WorkQueue w, int r) {
1671 dl 1.115 WorkQueue[] ws; int m;
1672 dl 1.200 if ((ws = workQueues) != null && (m = ws.length - 1) > 0 && w != null) {
1673     int ss = w.scanState; // initially non-negative
1674     for (int origin = r & m, k = origin, oldSum = 0, checkSum = 0;;) {
1675     WorkQueue q; ForkJoinTask<?>[] a; ForkJoinTask<?> t;
1676     int b, n; long c;
1677     if ((q = ws[k]) != null) {
1678     if ((n = (b = q.base) - q.top) < 0 &&
1679     (a = q.array) != null) { // non-empty
1680     long i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1681     if ((t = ((ForkJoinTask<?>)
1682     U.getObjectVolatile(a, i))) != null &&
1683     q.base == b) {
1684     if (ss >= 0) {
1685     if (U.compareAndSwapObject(a, i, t, null)) {
1686     q.base = b + 1;
1687     if (n < -1) // signal others
1688     signalWork(ws, q);
1689     return t;
1690     }
1691     }
1692     else if (oldSum == 0 && // try to activate
1693     w.scanState < 0)
1694     tryRelease(c = ctl, ws[m & (int)c], AC_UNIT);
1695 dl 1.178 }
1696 dl 1.200 if (ss < 0) // refresh
1697     ss = w.scanState;
1698     r ^= r << 1; r ^= r >>> 3; r ^= r << 10;
1699     origin = k = r & m; // move and rescan
1700     oldSum = checkSum = 0;
1701     continue;
1702     }
1703     checkSum += b;
1704     }
1705     if ((k = (k + 1) & m) == origin) { // continue until stable
1706     if ((ss >= 0 || (ss == (ss = w.scanState))) &&
1707     oldSum == (oldSum = checkSum)) {
1708 dl 1.210 if (ss < 0 || w.qlock < 0) // already inactive
1709 dl 1.200 break;
1710     int ns = ss | INACTIVE; // try to inactivate
1711     long nc = ((SP_MASK & ns) |
1712     (UC_MASK & ((c = ctl) - AC_UNIT)));
1713     w.stackPred = (int)c; // hold prev stack top
1714     U.putInt(w, QSCANSTATE, ns);
1715     if (U.compareAndSwapLong(this, CTL, c, nc))
1716     ss = ns;
1717     else
1718     w.scanState = ss; // back out
1719 dl 1.174 }
1720 dl 1.200 checkSum = 0;
1721 dl 1.115 }
1722     }
1723 dl 1.52 }
1724 dl 1.200 return null;
1725 dl 1.14 }
1726    
1727     /**
1728 dl 1.200 * Possibly blocks worker w waiting for a task to steal, or
1729     * returns false if the worker should terminate. If inactivating
1730     * w has caused the pool to become quiescent, checks for pool
1731 dl 1.178 * termination, and, so long as this is not the only worker, waits
1732 dl 1.200 * for up to a given duration. On timeout, if ctl has not
1733     * changed, terminates the worker, which will in turn wake up
1734 dl 1.178 * another worker to possibly repeat this process.
1735 dl 1.52 *
1736 dl 1.78 * @param w the calling worker
1737 dl 1.200 * param r a random seed (for spins)
1738     * @return false if the worker should terminate
1739 dl 1.14 */
1740 dl 1.200 private boolean awaitWork(WorkQueue w, int r) {
1741     if (w == null || w.qlock < 0) // w is terminating
1742     return false;
1743     for (int pred = w.stackPred, spins = SPINS, ss;;) {
1744     if ((ss = w.scanState) >= 0)
1745     break;
1746     else if (spins > 0) {
1747     r ^= r << 6; r ^= r >>> 21; r ^= r << 7;
1748     if (r >= 0 && --spins == 0) { // randomize spins
1749     WorkQueue v; WorkQueue[] ws; int s, j;
1750     if (pred != 0 && (ws = workQueues) != null &&
1751     (j = pred & SMASK) < ws.length &&
1752     (v = ws[j]) != null && // see if pred parking
1753     (v.parker == null || v.scanState >= 0))
1754 jsr166 1.202 spins = SPINS; // continue spinning
1755 dl 1.200 else if ((s = w.nsteals) != 0) {
1756     w.nsteals = 0; // collect steals
1757     U.getAndAddLong(this, STEALCOUNT, s);
1758     }
1759     }
1760 dl 1.177 }
1761 dl 1.200 else if (w.qlock < 0) // recheck after spins
1762     return false;
1763     else if (!Thread.interrupted()) {
1764     long c, prevctl, parkTime, deadline;
1765     int ac = (int)((c = ctl) >> AC_SHIFT) + (config & SMASK);
1766 dl 1.210 if ((ac <= 0 && tryTerminate(false, false)) ||
1767     (runState & STOP) != 0) // pool terminating
1768 dl 1.200 return false;
1769     if (ac <= 0 && ss == (int)c) { // is last waiter
1770     prevctl = (UC_MASK & (c + AC_UNIT)) | (SP_MASK & pred);
1771 dl 1.205 int t = (short)(c >>> TC_SHIFT); // shrink excess spares
1772     if (t > 2 && U.compareAndSwapLong(this, CTL, c, prevctl))
1773 dl 1.208 return false; // else use timed wait
1774 dl 1.205 parkTime = IDLE_TIMEOUT * ((t >= 0) ? 1 : 1 - t);
1775 dl 1.178 deadline = System.nanoTime() + parkTime - TIMEOUT_SLOP;
1776     }
1777     else
1778 dl 1.200 prevctl = parkTime = deadline = 0L;
1779     Thread wt = Thread.currentThread();
1780     U.putObject(wt, PARKBLOCKER, this); // emulate LockSupport
1781     w.parker = wt;
1782     if (w.scanState < 0 && ctl == c) // recheck before park
1783     U.park(false, parkTime);
1784     U.putOrderedObject(w, QPARKER, null);
1785     U.putObject(wt, PARKBLOCKER, null);
1786     if (w.scanState >= 0)
1787     break;
1788     if (parkTime != 0L && ctl == c &&
1789     deadline - System.nanoTime() <= 0L &&
1790     U.compareAndSwapLong(this, CTL, c, prevctl))
1791     return false; // shrink pool
1792 dl 1.120 }
1793     }
1794 dl 1.200 return true;
1795 dl 1.178 }
1796    
1797 dl 1.200 // Joining tasks
1798    
1799 dl 1.178 /**
1800 dl 1.200 * Tries to steal and run tasks within the target's computation.
1801     * Uses a variant of the top-level algorithm, restricted to tasks
1802     * with the given task as ancestor: It prefers taking and running
1803     * eligible tasks popped from the worker's own queue (via
1804     * popCC). Otherwise it scans others, randomly moving on
1805     * contention or execution, deciding to give up based on a
1806     * checksum (via return codes frob pollAndExecCC). The maxTasks
1807     * argument supports external usages; internal calls use zero,
1808     * allowing unbounded steps (external calls trap non-positive
1809     * values).
1810     *
1811     * @param w caller
1812 jsr166 1.202 * @param maxTasks if non-zero, the maximum number of other tasks to run
1813 dl 1.200 * @return task status on exit
1814     */
1815     final int helpComplete(WorkQueue w, CountedCompleter<?> task,
1816     int maxTasks) {
1817     WorkQueue[] ws; int s = 0, m;
1818     if ((ws = workQueues) != null && (m = ws.length - 1) >= 0 &&
1819     task != null && w != null) {
1820     int mode = w.config; // for popCC
1821     int r = w.hint ^ w.top; // arbitrary seed for origin
1822     int origin = r & m; // first queue to scan
1823     int h = 1; // 1:ran, >1:contended, <0:hash
1824     for (int k = origin, oldSum = 0, checkSum = 0;;) {
1825     CountedCompleter<?> p; WorkQueue q;
1826     if ((s = task.status) < 0)
1827     break;
1828     if (h == 1 && (p = w.popCC(task, mode)) != null) {
1829     p.doExec(); // run local task
1830     if (maxTasks != 0 && --maxTasks == 0)
1831     break;
1832     origin = k; // reset
1833     oldSum = checkSum = 0;
1834     }
1835     else { // poll other queues
1836     if ((q = ws[k]) == null)
1837     h = 0;
1838     else if ((h = q.pollAndExecCC(task)) < 0)
1839     checkSum += h;
1840     if (h > 0) {
1841     if (h == 1 && maxTasks != 0 && --maxTasks == 0)
1842     break;
1843     r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
1844     origin = k = r & m; // move and restart
1845     oldSum = checkSum = 0;
1846     }
1847     else if ((k = (k + 1) & m) == origin) {
1848     if (oldSum == (oldSum = checkSum))
1849     break;
1850     checkSum = 0;
1851     }
1852     }
1853 dl 1.178 }
1854     }
1855 dl 1.200 return s;
1856 dl 1.120 }
1857    
1858     /**
1859 dl 1.78 * Tries to locate and execute tasks for a stealer of the given
1860     * task, or in turn one of its stealers, Traces currentSteal ->
1861     * currentJoin links looking for a thread working on a descendant
1862     * of the given task and with a non-empty queue to steal back and
1863     * execute tasks from. The first call to this method upon a
1864     * waiting join will often entail scanning/search, (which is OK
1865     * because the joiner has nothing better to do), but this method
1866 dl 1.200 * leaves hints in workers to speed up subsequent calls.
1867 dl 1.78 *
1868 dl 1.200 * @param w caller
1869 dl 1.78 * @param task the task to join
1870     */
1871 dl 1.200 private void helpStealer(WorkQueue w, ForkJoinTask<?> task) {
1872     WorkQueue[] ws = workQueues;
1873     int oldSum = 0, checkSum, m;
1874     if (ws != null && (m = ws.length - 1) >= 0 && w != null &&
1875     task != null) {
1876     do { // restart point
1877     checkSum = 0; // for stability check
1878     ForkJoinTask<?> subtask;
1879     WorkQueue j = w, v; // v is subtask stealer
1880     descent: for (subtask = task; subtask.status >= 0; ) {
1881     for (int h = j.hint | 1, k = 0, i; ; k += 2) {
1882     if (k > m) // can't find stealer
1883     break descent;
1884     if ((v = ws[i = (h + k) & m]) != null) {
1885     if (v.currentSteal == subtask) {
1886     j.hint = i;
1887 dl 1.95 break;
1888     }
1889 dl 1.200 checkSum += v.base;
1890 dl 1.78 }
1891     }
1892 dl 1.200 for (;;) { // help v or descend
1893 jsr166 1.195 ForkJoinTask<?>[] a; int b;
1894 dl 1.200 checkSum += (b = v.base);
1895     ForkJoinTask<?> next = v.currentJoin;
1896     if (subtask.status < 0 || j.currentJoin != subtask ||
1897     v.currentSteal != subtask) // stale
1898     break descent;
1899     if (b - v.top >= 0 || (a = v.array) == null) {
1900     if ((subtask = next) == null)
1901     break descent;
1902     j = v;
1903     break;
1904 dl 1.95 }
1905 dl 1.200 int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1906     ForkJoinTask<?> t = ((ForkJoinTask<?>)
1907     U.getObjectVolatile(a, i));
1908     if (v.base == b) {
1909     if (t == null) // stale
1910     break descent;
1911     if (U.compareAndSwapObject(a, i, t, null)) {
1912     v.base = b + 1;
1913     ForkJoinTask<?> ps = w.currentSteal;
1914 dl 1.205 int top = w.top;
1915     do {
1916     U.putOrderedObject(w, QCURRENTSTEAL, t);
1917     t.doExec(); // clear local tasks too
1918     } while (task.status >= 0 &&
1919     w.top != top &&
1920     (t = w.pop()) != null);
1921 dl 1.200 U.putOrderedObject(w, QCURRENTSTEAL, ps);
1922 dl 1.205 if (w.base != w.top)
1923 dl 1.200 return; // can't further help
1924 dl 1.95 }
1925 dl 1.78 }
1926 dl 1.52 }
1927 dl 1.19 }
1928 dl 1.200 } while (task.status >= 0 && oldSum != (oldSum = checkSum));
1929 dl 1.14 }
1930 dl 1.22 }
1931    
1932 dl 1.52 /**
1933 dl 1.200 * Tries to decrement active count (sometimes implicitly) and
1934     * possibly release or create a compensating worker in preparation
1935     * for blocking. Returns false (retryable by caller), on
1936 dl 1.208 * contention, detected staleness, instability, or termination.
1937 dl 1.105 *
1938 dl 1.200 * @param w caller
1939 dl 1.19 */
1940 dl 1.200 private boolean tryCompensate(WorkQueue w) {
1941     boolean canBlock;
1942     WorkQueue[] ws; long c; int m, pc, sp;
1943     if (w == null || w.qlock < 0 || // caller terminating
1944     (ws = workQueues) == null || (m = ws.length - 1) <= 0 ||
1945     (pc = config & SMASK) == 0) // parallelism disabled
1946     canBlock = false;
1947     else if ((sp = (int)(c = ctl)) != 0) // release idle worker
1948     canBlock = tryRelease(c, ws[sp & m], 0L);
1949     else {
1950     int ac = (int)(c >> AC_SHIFT) + pc;
1951     int tc = (short)(c >> TC_SHIFT) + pc;
1952     int nbusy = 0; // validate saturation
1953     for (int i = 0; i <= m; ++i) { // two passes of odd indices
1954     WorkQueue v;
1955     if ((v = ws[((i << 1) | 1) & m]) != null) {
1956     if ((v.scanState & SCANNING) != 0)
1957 dl 1.190 break;
1958 dl 1.200 ++nbusy;
1959 dl 1.178 }
1960 dl 1.52 }
1961 dl 1.200 if (nbusy != (tc << 1) || ctl != c)
1962     canBlock = false; // unstable or stale
1963     else if (tc >= pc && ac > 1 && w.isEmpty()) {
1964     long nc = ((AC_MASK & (c - AC_UNIT)) |
1965     (~AC_MASK & c)); // uncompensated
1966     canBlock = U.compareAndSwapLong(this, CTL, c, nc);
1967 dl 1.105 }
1968 dl 1.208 else if (tc >= MAX_CAP ||
1969     (this == common && tc >= pc + commonMaxSpares))
1970 dl 1.200 throw new RejectedExecutionException(
1971     "Thread limit exceeded replacing blocked worker");
1972     else { // similar to tryAddWorker
1973     boolean add = false; int rs; // CAS within lock
1974     long nc = ((AC_MASK & c) |
1975     (TC_MASK & (c + TC_UNIT)));
1976     if (((rs = lockRunState()) & STOP) == 0)
1977     add = U.compareAndSwapLong(this, CTL, c, nc);
1978     unlockRunState(rs, rs & ~RSLOCK);
1979     canBlock = add && createWorker(); // throws on exception
1980 dl 1.90 }
1981     }
1982 dl 1.200 return canBlock;
1983 dl 1.90 }
1984    
1985     /**
1986 dl 1.200 * Helps and/or blocks until the given task is done or timeout.
1987 dl 1.90 *
1988 dl 1.200 * @param w caller
1989 dl 1.90 * @param task the task
1990 dl 1.200 * @param if nonzero, deadline for timed waits
1991 dl 1.90 * @return task status on exit
1992     */
1993 dl 1.200 final int awaitJoin(WorkQueue w, ForkJoinTask<?> task, long deadline) {
1994 dl 1.105 int s = 0;
1995 dl 1.200 if (task != null && w != null) {
1996     ForkJoinTask<?> prevJoin = w.currentJoin;
1997     U.putOrderedObject(w, QCURRENTJOIN, task);
1998     CountedCompleter<?> cc = (task instanceof CountedCompleter) ?
1999     (CountedCompleter<?>)task : null;
2000     for (;;) {
2001     if ((s = task.status) < 0)
2002     break;
2003     if (cc != null)
2004     helpComplete(w, cc, 0);
2005     else if (w.base == w.top || w.tryRemoveAndExec(task))
2006     helpStealer(w, task);
2007     if ((s = task.status) < 0)
2008     break;
2009     long ms, ns;
2010     if (deadline == 0L)
2011     ms = 0L;
2012     else if ((ns = deadline - System.nanoTime()) <= 0L)
2013     break;
2014     else if ((ms = TimeUnit.NANOSECONDS.toMillis(ns)) <= 0L)
2015     ms = 1L;
2016     if (tryCompensate(w)) {
2017     task.internalWait(ms);
2018     U.getAndAddLong(this, CTL, AC_UNIT);
2019 dl 1.90 }
2020     }
2021 dl 1.200 U.putOrderedObject(w, QCURRENTJOIN, prevJoin);
2022 dl 1.90 }
2023 dl 1.94 return s;
2024 dl 1.90 }
2025    
2026 dl 1.200 // Specialized scanning
2027 dl 1.90
2028     /**
2029     * Returns a (probably) non-empty steal queue, if one is found
2030 dl 1.131 * during a scan, else null. This method must be retried by
2031     * caller if, by the time it tries to use the queue, it is empty.
2032 dl 1.78 */
2033 dl 1.178 private WorkQueue findNonEmptyStealQueue() {
2034 dl 1.211 WorkQueue[] ws; int m; // one-shot version of scan loop
2035     int r = ThreadLocalRandom.nextSecondarySeed();
2036     if ((ws = workQueues) != null && (m = ws.length - 1) >= 0) {
2037     for (int origin = r & m, k = origin, oldSum = 0, checkSum = 0;;) {
2038     WorkQueue q; int b;
2039     if ((q = ws[k]) != null) {
2040     if ((b = q.base) - q.top < 0)
2041     return q;
2042     checkSum += b;
2043     }
2044     if ((k = (k + 1) & m) == origin) {
2045     if (oldSum == (oldSum = checkSum))
2046     break;
2047     checkSum = 0;
2048 dl 1.52 }
2049     }
2050 dl 1.211 }
2051 dl 1.200 return null;
2052 dl 1.22 }
2053    
2054     /**
2055 dl 1.78 * Runs tasks until {@code isQuiescent()}. We piggyback on
2056     * active count ctl maintenance, but rather than blocking
2057     * when tasks cannot be found, we rescan until all others cannot
2058     * find tasks either.
2059     */
2060     final void helpQuiescePool(WorkQueue w) {
2061 dl 1.211 ForkJoinTask<?> ps = w.currentSteal; // save context
2062 dl 1.78 for (boolean active = true;;) {
2063 dl 1.131 long c; WorkQueue q; ForkJoinTask<?> t; int b;
2064 dl 1.211 w.execLocalTasks(); // run locals before each scan
2065 dl 1.178 if ((q = findNonEmptyStealQueue()) != null) {
2066 dl 1.78 if (!active) { // re-establish active count
2067     active = true;
2068 dl 1.200 U.getAndAddLong(this, CTL, AC_UNIT);
2069     }
2070     if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null) {
2071     U.putOrderedObject(w, QCURRENTSTEAL, t);
2072     t.doExec();
2073     ++w.nsteals;
2074 dl 1.178 }
2075 dl 1.78 }
2076 jsr166 1.194 else if (active) { // decrement active count without queuing
2077 dl 1.200 long nc = (AC_MASK & ((c = ctl) - AC_UNIT)) | (~AC_MASK & c);
2078     if ((int)(nc >> AC_SHIFT) + (config & SMASK) <= 0)
2079 dl 1.185 break; // bypass decrement-then-increment
2080 dl 1.131 if (U.compareAndSwapLong(this, CTL, c, nc))
2081 dl 1.78 active = false;
2082 dl 1.22 }
2083 dl 1.200 else if ((int)((c = ctl) >> AC_SHIFT) + (config & SMASK) <= 0 &&
2084     U.compareAndSwapLong(this, CTL, c, c + AC_UNIT))
2085 dl 1.185 break;
2086 dl 1.22 }
2087 dl 1.211 U.putOrderedObject(w, QCURRENTSTEAL, ps);
2088 dl 1.22 }
2089    
2090     /**
2091 jsr166 1.84 * Gets and removes a local or stolen task for the given worker.
2092 dl 1.78 *
2093     * @return a task, if available
2094 dl 1.22 */
2095 dl 1.78 final ForkJoinTask<?> nextTaskFor(WorkQueue w) {
2096     for (ForkJoinTask<?> t;;) {
2097 dl 1.90 WorkQueue q; int b;
2098 dl 1.78 if ((t = w.nextLocalTask()) != null)
2099     return t;
2100 dl 1.178 if ((q = findNonEmptyStealQueue()) == null)
2101 dl 1.78 return null;
2102 dl 1.172 if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
2103 dl 1.78 return t;
2104 dl 1.52 }
2105 dl 1.14 }
2106    
2107     /**
2108 dl 1.105 * Returns a cheap heuristic guide for task partitioning when
2109     * programmers, frameworks, tools, or languages have little or no
2110     * idea about task granularity. In essence by offering this
2111     * method, we ask users only about tradeoffs in overhead vs
2112     * expected throughput and its variance, rather than how finely to
2113     * partition tasks.
2114     *
2115     * In a steady state strict (tree-structured) computation, each
2116     * thread makes available for stealing enough tasks for other
2117     * threads to remain active. Inductively, if all threads play by
2118     * the same rules, each thread should make available only a
2119     * constant number of tasks.
2120     *
2121     * The minimum useful constant is just 1. But using a value of 1
2122     * would require immediate replenishment upon each steal to
2123     * maintain enough tasks, which is infeasible. Further,
2124     * partitionings/granularities of offered tasks should minimize
2125     * steal rates, which in general means that threads nearer the top
2126     * of computation tree should generate more than those nearer the
2127     * bottom. In perfect steady state, each thread is at
2128     * approximately the same level of computation tree. However,
2129     * producing extra tasks amortizes the uncertainty of progress and
2130     * diffusion assumptions.
2131     *
2132 jsr166 1.161 * So, users will want to use values larger (but not much larger)
2133 dl 1.105 * than 1 to both smooth over transient shortages and hedge
2134     * against uneven progress; as traded off against the cost of
2135     * extra task overhead. We leave the user to pick a threshold
2136     * value to compare with the results of this call to guide
2137     * decisions, but recommend values such as 3.
2138     *
2139     * When all threads are active, it is on average OK to estimate
2140     * surplus strictly locally. In steady-state, if one thread is
2141     * maintaining say 2 surplus tasks, then so are others. So we can
2142     * just use estimated queue length. However, this strategy alone
2143     * leads to serious mis-estimates in some non-steady-state
2144     * conditions (ramp-up, ramp-down, other stalls). We can detect
2145     * many of these by further considering the number of "idle"
2146     * threads, that are known to have zero queued tasks, so
2147     * compensate by a factor of (#idle/#active) threads.
2148     */
2149     static int getSurplusQueuedTaskCount() {
2150     Thread t; ForkJoinWorkerThread wt; ForkJoinPool pool; WorkQueue q;
2151     if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)) {
2152 dl 1.200 int p = (pool = (wt = (ForkJoinWorkerThread)t).pool).
2153     config & SMASK;
2154 dl 1.112 int n = (q = wt.workQueue).top - q.base;
2155 dl 1.105 int a = (int)(pool.ctl >> AC_SHIFT) + p;
2156 dl 1.112 return n - (a > (p >>>= 1) ? 0 :
2157     a > (p >>>= 1) ? 1 :
2158     a > (p >>>= 1) ? 2 :
2159     a > (p >>>= 1) ? 4 :
2160     8);
2161 dl 1.105 }
2162     return 0;
2163 dl 1.100 }
2164    
2165 dl 1.86 // Termination
2166 dl 1.14
2167     /**
2168 dl 1.210 * Possibly initiates and/or completes termination.
2169 dl 1.14 *
2170     * @param now if true, unconditionally terminate, else only
2171 dl 1.78 * if no work and no active workers
2172 jsr166 1.87 * @param enable if true, enable shutdown when next possible
2173 dl 1.14 * @return true if now terminating or terminated
2174 jsr166 1.1 */
2175 dl 1.86 private boolean tryTerminate(boolean now, boolean enable) {
2176 dl 1.200 int rs;
2177     if (this == common) // cannot shut down
2178 dl 1.105 return false;
2179 dl 1.210 if ((rs = runState) >= 0) {
2180 dl 1.131 if (!enable)
2181     return false;
2182 dl 1.210 rs = lockRunState(); // enter SHUTDOWN phase
2183 dl 1.200 unlockRunState(rs, (rs & ~RSLOCK) | SHUTDOWN);
2184     }
2185 dl 1.210
2186 jsr166 1.204 if ((rs & STOP) == 0) {
2187 dl 1.210 if (!now) { // check quiescence
2188 dl 1.211 for (long oldSum = 0L;;) { // repeat until stable
2189 dl 1.210 WorkQueue[] ws; WorkQueue w; int m, b; long c;
2190     long checkSum = ctl;
2191     if ((int)(checkSum >> AC_SHIFT) + (config & SMASK) > 0)
2192     return false; // still active workers
2193 dl 1.209 if ((ws = workQueues) == null || (m = ws.length - 1) <= 0)
2194 dl 1.210 break; // check queues
2195 dl 1.209 for (int i = 0; i <= m; ++i) {
2196     if ((w = ws[i]) != null) {
2197 dl 1.210 if ((b = w.base) != w.top || w.scanState >= 0 ||
2198     w.currentSteal != null) {
2199     tryRelease(c = ctl, ws[m & (int)c], AC_UNIT);
2200 dl 1.211 return false; // arrange for recheck
2201 dl 1.210 }
2202     checkSum += b;
2203 dl 1.209 if ((i & 1) == 0)
2204 dl 1.210 w.qlock = -1; // try to disable external
2205 dl 1.206 }
2206 dl 1.203 }
2207 dl 1.209 if (oldSum == (oldSum = checkSum))
2208 dl 1.210 break;
2209 dl 1.203 }
2210     }
2211 dl 1.210 if ((runState & STOP) == 0) {
2212     rs = lockRunState(); // enter STOP phase
2213     unlockRunState(rs, (rs & ~RSLOCK) | STOP);
2214     }
2215 dl 1.200 }
2216 dl 1.210
2217     int pass = 0; // 3 passes to help terminate
2218     for (long oldSum = 0L;;) { // or until done or stable
2219     WorkQueue[] ws; WorkQueue w; ForkJoinWorkerThread wt; int m;
2220     long checkSum = ctl;
2221     if ((short)(checkSum >>> TC_SHIFT) + (config & SMASK) <= 0 ||
2222     (ws = workQueues) == null || (m = ws.length - 1) <= 0) {
2223     if ((runState & TERMINATED) == 0) {
2224     rs = lockRunState(); // done
2225     unlockRunState(rs, (rs & ~RSLOCK) | TERMINATED);
2226     synchronized (this) { notifyAll(); } // for awaitTermination
2227     }
2228     break;
2229     }
2230     for (int i = 0; i <= m; ++i) {
2231     if ((w = ws[i]) != null) {
2232     checkSum += w.base;
2233     w.qlock = -1; // try to disable
2234     if (pass > 0) {
2235     w.cancelAll(); // clear queue
2236     if (pass > 1 && (wt = w.owner) != null) {
2237     if (!wt.isInterrupted()) {
2238     try { // unblock join
2239     wt.interrupt();
2240     } catch (Throwable ignore) {
2241 dl 1.200 }
2242     }
2243 dl 1.210 if (w.scanState < 0)
2244     U.unpark(wt); // wake up
2245 dl 1.200 }
2246 dl 1.101 }
2247 dl 1.78 }
2248     }
2249 dl 1.210 if (checkSum != oldSum) { // unstable
2250     oldSum = checkSum;
2251     pass = 0;
2252     }
2253     else if (pass > 3 && pass > m) // can't further help
2254     break;
2255     else if (++pass > 1) { // try to dequeue
2256     long c; int j = 0, sp; // bound attempts
2257     while (j++ <= m && (sp = (int)(c = ctl)) != 0)
2258     tryRelease(c, ws[sp & m], AC_UNIT);
2259 dl 1.200 }
2260     }
2261     return true;
2262     }
2263    
2264     // External operations
2265    
2266     /**
2267     * Full version of externalPush, handling uncommon cases, as well
2268     * as performing secondary initialization upon the first
2269     * submission of the first task to the pool. It also detects
2270     * first submission by an external thread and creates a new shared
2271     * queue if the one at index if empty or contended.
2272     *
2273     * @param task the task. Caller must ensure non-null.
2274     */
2275     private void externalSubmit(ForkJoinTask<?> task) {
2276     int r; // initialize caller's probe
2277     if ((r = ThreadLocalRandom.getProbe()) == 0) {
2278     ThreadLocalRandom.localInit();
2279     r = ThreadLocalRandom.getProbe();
2280     }
2281     for (;;) {
2282     WorkQueue[] ws; WorkQueue q; int rs, m, k;
2283     boolean move = false;
2284 dl 1.210 if ((rs = runState) < 0) {
2285     tryTerminate(false, false); // help terminate
2286 dl 1.200 throw new RejectedExecutionException();
2287 dl 1.210 }
2288 dl 1.200 else if ((rs & STARTED) == 0 || // initialize workQueues array
2289     ((ws = workQueues) == null || (m = ws.length - 1) < 0)) {
2290     int ns = 0;
2291     rs = lockRunState();
2292     try {
2293     if ((rs & STARTED) == 0) { // find power of two table size
2294     int p = config & SMASK; // ensure at least 2 slots
2295     int n = (p > 1) ? p - 1 : 1;
2296     n |= n >>> 1; n |= n >>> 2; n |= n >>> 4;
2297     n |= n >>> 8; n |= n >>> 16; n = (n + 1) << 1;
2298     workQueues = new WorkQueue[n];
2299     ns = STARTED;
2300 dl 1.78 }
2301 dl 1.200 } finally {
2302     unlockRunState(rs, (rs & ~RSLOCK) | ns);
2303 dl 1.52 }
2304     }
2305 dl 1.200 else if ((q = ws[k = r & m & SQMASK]) != null) {
2306     if (q.qlock == 0 && U.compareAndSwapInt(q, QLOCK, 0, 1)) {
2307     ForkJoinTask<?>[] a = q.array;
2308     int s = q.top;
2309     boolean submitted = false; // initial submission or resizing
2310     try { // locked version of push
2311     if ((a != null && a.length > s + 1 - q.base) ||
2312     (a = q.growArray()) != null) {
2313     int j = (((a.length - 1) & s) << ASHIFT) + ABASE;
2314     U.putOrderedObject(a, j, task);
2315     U.putOrderedInt(q, QTOP, s + 1);
2316     submitted = true;
2317 dl 1.86 }
2318 dl 1.200 } finally {
2319 dl 1.209 U.compareAndSwapInt(q, QLOCK, 1, 0);
2320 dl 1.200 }
2321     if (submitted) {
2322     signalWork(ws, q);
2323     return;
2324 dl 1.78 }
2325 dl 1.52 }
2326 dl 1.200 move = true; // move on failure
2327 dl 1.52 }
2328 dl 1.200 else if (((rs = runState) & RSLOCK) == 0) { // create new queue
2329     q = new WorkQueue(this, null);
2330     q.hint = r;
2331     q.config = k | SHARED_QUEUE;
2332 dl 1.210 q.scanState = INACTIVE;
2333 dl 1.200 rs = lockRunState(); // publish index
2334 dl 1.209 if (rs > 0 && (ws = workQueues) != null &&
2335     k < ws.length && ws[k] == null)
2336 dl 1.200 ws[k] = q; // else terminated
2337     unlockRunState(rs, rs & ~RSLOCK);
2338     }
2339     else
2340     move = true; // move if busy
2341     if (move)
2342     r = ThreadLocalRandom.advanceProbe(r);
2343 dl 1.52 }
2344     }
2345    
2346 dl 1.200 /**
2347     * Tries to add the given task to a submission queue at
2348     * submitter's current queue. Only the (vastly) most common path
2349     * is directly handled in this method, while screening for need
2350     * for externalSubmit.
2351     *
2352     * @param task the task. Caller must ensure non-null.
2353     */
2354     final void externalPush(ForkJoinTask<?> task) {
2355     WorkQueue[] ws; WorkQueue q; int m;
2356     int r = ThreadLocalRandom.getProbe();
2357 dl 1.205 int rs = runState;
2358 dl 1.200 if ((ws = workQueues) != null && (m = (ws.length - 1)) >= 0 &&
2359 dl 1.205 (q = ws[m & r & SQMASK]) != null && r != 0 && rs > 0 &&
2360 dl 1.200 U.compareAndSwapInt(q, QLOCK, 0, 1)) {
2361     ForkJoinTask<?>[] a; int am, n, s;
2362     if ((a = q.array) != null &&
2363     (am = a.length - 1) > (n = (s = q.top) - q.base)) {
2364     int j = ((am & s) << ASHIFT) + ABASE;
2365     U.putOrderedObject(a, j, task);
2366     U.putOrderedInt(q, QTOP, s + 1);
2367     U.putOrderedInt(q, QLOCK, 0);
2368 dl 1.205 if (n <= 1)
2369 dl 1.200 signalWork(ws, q);
2370     return;
2371     }
2372 dl 1.209 U.compareAndSwapInt(q, QLOCK, 1, 0);
2373 dl 1.200 }
2374     externalSubmit(task);
2375     }
2376 dl 1.105
2377     /**
2378 dl 1.200 * Returns common pool queue for an external thread
2379 dl 1.105 */
2380     static WorkQueue commonSubmitterQueue() {
2381 dl 1.200 ForkJoinPool p = common;
2382     int r = ThreadLocalRandom.getProbe();
2383     WorkQueue[] ws; int m;
2384     return (p != null && (ws = p.workQueues) != null &&
2385 dl 1.105 (m = ws.length - 1) >= 0) ?
2386 dl 1.200 ws[m & r & SQMASK] : null;
2387 dl 1.105 }
2388    
2389     /**
2390 dl 1.200 * Performs tryUnpush for an external submitter: Finds queue,
2391     * locks if apparently non-empty, validates upon locking, and
2392     * adjusts top. Each check can fail but rarely does.
2393 dl 1.105 */
2394 dl 1.178 final boolean tryExternalUnpush(ForkJoinTask<?> task) {
2395 dl 1.200 WorkQueue[] ws; WorkQueue w; ForkJoinTask<?>[] a; int m, s;
2396     int r = ThreadLocalRandom.getProbe();
2397     if ((ws = workQueues) != null && (m = ws.length - 1) >= 0 &&
2398     (w = ws[m & r & SQMASK]) != null &&
2399     (a = w.array) != null && (s = w.top) != w.base) {
2400 dl 1.115 long j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE;
2401 dl 1.200 if (U.compareAndSwapInt(w, QLOCK, 0, 1)) {
2402     if (w.top == s && w.array == a &&
2403     U.getObject(a, j) == task &&
2404 dl 1.178 U.compareAndSwapObject(a, j, task, null)) {
2405 dl 1.200 U.putOrderedInt(w, QTOP, s - 1);
2406     U.putOrderedInt(w, QLOCK, 0);
2407     return true;
2408 dl 1.115 }
2409 dl 1.209 U.compareAndSwapInt(w, QLOCK, 1, 0);
2410 dl 1.105 }
2411     }
2412 dl 1.200 return false;
2413 dl 1.105 }
2414    
2415 dl 1.200 /**
2416     * Performs helpComplete for an external submitter
2417     */
2418 dl 1.190 final int externalHelpComplete(CountedCompleter<?> task, int maxTasks) {
2419 dl 1.200 WorkQueue[] ws; int n;
2420     int r = ThreadLocalRandom.getProbe();
2421     return ((ws = workQueues) == null || (n = ws.length) == 0) ? 0 :
2422     helpComplete(ws[(n - 1) & r & SQMASK], task, maxTasks);
2423 dl 1.105 }
2424    
2425 dl 1.52 // Exported methods
2426 jsr166 1.1
2427     // Constructors
2428    
2429     /**
2430 jsr166 1.9 * Creates a {@code ForkJoinPool} with parallelism equal to {@link
2431 dl 1.18 * java.lang.Runtime#availableProcessors}, using the {@linkplain
2432     * #defaultForkJoinWorkerThreadFactory default thread factory},
2433     * no UncaughtExceptionHandler, and non-async LIFO processing mode.
2434 jsr166 1.1 *
2435     * @throws SecurityException if a security manager exists and
2436     * the caller is not permitted to modify threads
2437     * because it does not hold {@link
2438     * java.lang.RuntimePermission}{@code ("modifyThread")}
2439     */
2440     public ForkJoinPool() {
2441 jsr166 1.148 this(Math.min(MAX_CAP, Runtime.getRuntime().availableProcessors()),
2442     defaultForkJoinWorkerThreadFactory, null, false);
2443 jsr166 1.1 }
2444    
2445     /**
2446 jsr166 1.9 * Creates a {@code ForkJoinPool} with the indicated parallelism
2447 dl 1.18 * level, the {@linkplain
2448     * #defaultForkJoinWorkerThreadFactory default thread factory},
2449     * no UncaughtExceptionHandler, and non-async LIFO processing mode.
2450 jsr166 1.1 *
2451 jsr166 1.9 * @param parallelism the parallelism level
2452 jsr166 1.1 * @throws IllegalArgumentException if parallelism less than or
2453 jsr166 1.11 * equal to zero, or greater than implementation limit
2454 jsr166 1.1 * @throws SecurityException if a security manager exists and
2455     * the caller is not permitted to modify threads
2456     * because it does not hold {@link
2457     * java.lang.RuntimePermission}{@code ("modifyThread")}
2458     */
2459     public ForkJoinPool(int parallelism) {
2460 dl 1.18 this(parallelism, defaultForkJoinWorkerThreadFactory, null, false);
2461 jsr166 1.1 }
2462    
2463     /**
2464 dl 1.18 * Creates a {@code ForkJoinPool} with the given parameters.
2465 jsr166 1.1 *
2466 dl 1.18 * @param parallelism the parallelism level. For default value,
2467     * use {@link java.lang.Runtime#availableProcessors}.
2468     * @param factory the factory for creating new threads. For default value,
2469     * use {@link #defaultForkJoinWorkerThreadFactory}.
2470 dl 1.19 * @param handler the handler for internal worker threads that
2471     * terminate due to unrecoverable errors encountered while executing
2472 jsr166 1.31 * tasks. For default value, use {@code null}.
2473 dl 1.19 * @param asyncMode if true,
2474 dl 1.18 * establishes local first-in-first-out scheduling mode for forked
2475     * tasks that are never joined. This mode may be more appropriate
2476     * than default locally stack-based mode in applications in which
2477     * worker threads only process event-style asynchronous tasks.
2478 jsr166 1.31 * For default value, use {@code false}.
2479 jsr166 1.1 * @throws IllegalArgumentException if parallelism less than or
2480 jsr166 1.11 * equal to zero, or greater than implementation limit
2481     * @throws NullPointerException if the factory is null
2482 jsr166 1.1 * @throws SecurityException if a security manager exists and
2483     * the caller is not permitted to modify threads
2484     * because it does not hold {@link
2485     * java.lang.RuntimePermission}{@code ("modifyThread")}
2486     */
2487 dl 1.19 public ForkJoinPool(int parallelism,
2488 dl 1.18 ForkJoinWorkerThreadFactory factory,
2489 jsr166 1.156 UncaughtExceptionHandler handler,
2490 dl 1.18 boolean asyncMode) {
2491 dl 1.152 this(checkParallelism(parallelism),
2492     checkFactory(factory),
2493     handler,
2494 jsr166 1.201 asyncMode ? FIFO_QUEUE : LIFO_QUEUE,
2495 dl 1.152 "ForkJoinPool-" + nextPoolId() + "-worker-");
2496 dl 1.14 checkPermission();
2497 dl 1.152 }
2498    
2499     private static int checkParallelism(int parallelism) {
2500     if (parallelism <= 0 || parallelism > MAX_CAP)
2501     throw new IllegalArgumentException();
2502     return parallelism;
2503     }
2504    
2505     private static ForkJoinWorkerThreadFactory checkFactory
2506     (ForkJoinWorkerThreadFactory factory) {
2507 dl 1.14 if (factory == null)
2508     throw new NullPointerException();
2509 dl 1.152 return factory;
2510     }
2511    
2512     /**
2513     * Creates a {@code ForkJoinPool} with the given parameters, without
2514     * any security checks or parameter validation. Invoked directly by
2515     * makeCommonPool.
2516     */
2517     private ForkJoinPool(int parallelism,
2518     ForkJoinWorkerThreadFactory factory,
2519 jsr166 1.156 UncaughtExceptionHandler handler,
2520 dl 1.185 int mode,
2521 dl 1.152 String workerNamePrefix) {
2522     this.workerNamePrefix = workerNamePrefix;
2523 jsr166 1.1 this.factory = factory;
2524 dl 1.18 this.ueh = handler;
2525 dl 1.200 this.config = (parallelism & SMASK) | mode;
2526 dl 1.52 long np = (long)(-parallelism); // offset ctl counts
2527     this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2528 dl 1.101 }
2529    
2530     /**
2531 dl 1.128 * Returns the common pool instance. This pool is statically
2532 dl 1.134 * constructed; its run state is unaffected by attempts to {@link
2533     * #shutdown} or {@link #shutdownNow}. However this pool and any
2534     * ongoing processing are automatically terminated upon program
2535     * {@link System#exit}. Any program that relies on asynchronous
2536     * task processing to complete before program termination should
2537 jsr166 1.158 * invoke {@code commonPool().}{@link #awaitQuiescence awaitQuiescence},
2538     * before exit.
2539 dl 1.100 *
2540     * @return the common pool instance
2541 jsr166 1.138 * @since 1.8
2542 dl 1.100 */
2543     public static ForkJoinPool commonPool() {
2544 dl 1.134 // assert common != null : "static init error";
2545     return common;
2546 dl 1.100 }
2547    
2548 jsr166 1.1 // Execution methods
2549    
2550     /**
2551     * Performs the given task, returning its result upon completion.
2552 dl 1.52 * If the computation encounters an unchecked Exception or Error,
2553     * it is rethrown as the outcome of this invocation. Rethrown
2554     * exceptions behave in the same way as regular exceptions, but,
2555     * when possible, contain stack traces (as displayed for example
2556     * using {@code ex.printStackTrace()}) of both the current thread
2557     * as well as the thread actually encountering the exception;
2558     * minimally only the latter.
2559 jsr166 1.1 *
2560     * @param task the task
2561 jsr166 1.191 * @param <T> the type of the task's result
2562 jsr166 1.1 * @return the task's result
2563 jsr166 1.11 * @throws NullPointerException if the task is null
2564     * @throws RejectedExecutionException if the task cannot be
2565     * scheduled for execution
2566 jsr166 1.1 */
2567     public <T> T invoke(ForkJoinTask<T> task) {
2568 dl 1.90 if (task == null)
2569     throw new NullPointerException();
2570 dl 1.105 externalPush(task);
2571 dl 1.78 return task.join();
2572 jsr166 1.1 }
2573    
2574     /**
2575     * Arranges for (asynchronous) execution of the given task.
2576     *
2577     * @param task the task
2578 jsr166 1.11 * @throws NullPointerException if the task is null
2579     * @throws RejectedExecutionException if the task cannot be
2580     * scheduled for execution
2581 jsr166 1.1 */
2582 jsr166 1.8 public void execute(ForkJoinTask<?> task) {
2583 dl 1.90 if (task == null)
2584     throw new NullPointerException();
2585 dl 1.105 externalPush(task);
2586 jsr166 1.1 }
2587    
2588     // AbstractExecutorService methods
2589    
2590 jsr166 1.11 /**
2591     * @throws NullPointerException if the task is null
2592     * @throws RejectedExecutionException if the task cannot be
2593     * scheduled for execution
2594     */
2595 jsr166 1.1 public void execute(Runnable task) {
2596 dl 1.41 if (task == null)
2597     throw new NullPointerException();
2598 jsr166 1.2 ForkJoinTask<?> job;
2599 jsr166 1.3 if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2600     job = (ForkJoinTask<?>) task;
2601 jsr166 1.2 else
2602 dl 1.152 job = new ForkJoinTask.RunnableExecuteAction(task);
2603 dl 1.105 externalPush(job);
2604 jsr166 1.1 }
2605    
2606 jsr166 1.11 /**
2607 dl 1.18 * Submits a ForkJoinTask for execution.
2608     *
2609     * @param task the task to submit
2610 jsr166 1.191 * @param <T> the type of the task's result
2611 dl 1.18 * @return the task
2612     * @throws NullPointerException if the task is null
2613     * @throws RejectedExecutionException if the task cannot be
2614     * scheduled for execution
2615     */
2616     public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
2617 dl 1.90 if (task == null)
2618     throw new NullPointerException();
2619 dl 1.105 externalPush(task);
2620 dl 1.18 return task;
2621     }
2622    
2623     /**
2624 jsr166 1.11 * @throws NullPointerException if the task is null
2625     * @throws RejectedExecutionException if the task cannot be
2626     * scheduled for execution
2627     */
2628 jsr166 1.1 public <T> ForkJoinTask<T> submit(Callable<T> task) {
2629 dl 1.90 ForkJoinTask<T> job = new ForkJoinTask.AdaptedCallable<T>(task);
2630 dl 1.105 externalPush(job);
2631 jsr166 1.1 return job;
2632     }
2633    
2634 jsr166 1.11 /**
2635     * @throws NullPointerException if the task is null
2636     * @throws RejectedExecutionException if the task cannot be
2637     * scheduled for execution
2638     */
2639 jsr166 1.1 public <T> ForkJoinTask<T> submit(Runnable task, T result) {
2640 dl 1.90 ForkJoinTask<T> job = new ForkJoinTask.AdaptedRunnable<T>(task, result);
2641 dl 1.105 externalPush(job);
2642 jsr166 1.1 return job;
2643     }
2644    
2645 jsr166 1.11 /**
2646     * @throws NullPointerException if the task is null
2647     * @throws RejectedExecutionException if the task cannot be
2648     * scheduled for execution
2649     */
2650 jsr166 1.1 public ForkJoinTask<?> submit(Runnable task) {
2651 dl 1.41 if (task == null)
2652     throw new NullPointerException();
2653 jsr166 1.2 ForkJoinTask<?> job;
2654 jsr166 1.3 if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2655     job = (ForkJoinTask<?>) task;
2656 jsr166 1.2 else
2657 dl 1.90 job = new ForkJoinTask.AdaptedRunnableAction(task);
2658 dl 1.105 externalPush(job);
2659 jsr166 1.1 return job;
2660     }
2661    
2662     /**
2663 jsr166 1.11 * @throws NullPointerException {@inheritDoc}
2664     * @throws RejectedExecutionException {@inheritDoc}
2665     */
2666 jsr166 1.1 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
2667 dl 1.86 // In previous versions of this class, this method constructed
2668     // a task to run ForkJoinTask.invokeAll, but now external
2669     // invocation of multiple tasks is at least as efficient.
2670 jsr166 1.199 ArrayList<Future<T>> futures = new ArrayList<>(tasks.size());
2671 jsr166 1.1
2672 dl 1.86 boolean done = false;
2673     try {
2674     for (Callable<T> t : tasks) {
2675 dl 1.90 ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
2676 jsr166 1.144 futures.add(f);
2677 dl 1.105 externalPush(f);
2678 dl 1.86 }
2679 jsr166 1.143 for (int i = 0, size = futures.size(); i < size; i++)
2680     ((ForkJoinTask<?>)futures.get(i)).quietlyJoin();
2681 dl 1.86 done = true;
2682     return futures;
2683     } finally {
2684     if (!done)
2685 jsr166 1.143 for (int i = 0, size = futures.size(); i < size; i++)
2686     futures.get(i).cancel(false);
2687 jsr166 1.1 }
2688     }
2689    
2690     /**
2691     * Returns the factory used for constructing new workers.
2692     *
2693     * @return the factory used for constructing new workers
2694     */
2695     public ForkJoinWorkerThreadFactory getFactory() {
2696     return factory;
2697     }
2698    
2699     /**
2700     * Returns the handler for internal worker threads that terminate
2701     * due to unrecoverable errors encountered while executing tasks.
2702     *
2703 jsr166 1.4 * @return the handler, or {@code null} if none
2704 jsr166 1.1 */
2705 jsr166 1.156 public UncaughtExceptionHandler getUncaughtExceptionHandler() {
2706 dl 1.14 return ueh;
2707 jsr166 1.1 }
2708    
2709     /**
2710 jsr166 1.9 * Returns the targeted parallelism level of this pool.
2711 jsr166 1.1 *
2712 jsr166 1.9 * @return the targeted parallelism level of this pool
2713 jsr166 1.1 */
2714     public int getParallelism() {
2715 dl 1.185 int par;
2716 dl 1.200 return ((par = config & SMASK) > 0) ? par : 1;
2717 jsr166 1.1 }
2718    
2719     /**
2720 dl 1.100 * Returns the targeted parallelism level of the common pool.
2721     *
2722     * @return the targeted parallelism level of the common pool
2723 jsr166 1.138 * @since 1.8
2724 dl 1.100 */
2725     public static int getCommonPoolParallelism() {
2726 dl 1.134 return commonParallelism;
2727 dl 1.100 }
2728    
2729     /**
2730 jsr166 1.1 * Returns the number of worker threads that have started but not
2731 jsr166 1.34 * yet terminated. The result returned by this method may differ
2732 jsr166 1.4 * from {@link #getParallelism} when threads are created to
2733 jsr166 1.1 * maintain parallelism when others are cooperatively blocked.
2734     *
2735     * @return the number of worker threads
2736     */
2737     public int getPoolSize() {
2738 dl 1.200 return (config & SMASK) + (short)(ctl >>> TC_SHIFT);
2739 jsr166 1.1 }
2740    
2741     /**
2742 jsr166 1.4 * Returns {@code true} if this pool uses local first-in-first-out
2743 jsr166 1.1 * scheduling mode for forked tasks that are never joined.
2744     *
2745 jsr166 1.4 * @return {@code true} if this pool uses async mode
2746 jsr166 1.1 */
2747     public boolean getAsyncMode() {
2748 dl 1.200 return (config & FIFO_QUEUE) != 0;
2749 jsr166 1.1 }
2750    
2751     /**
2752     * Returns an estimate of the number of worker threads that are
2753     * not blocked waiting to join tasks or for other managed
2754 dl 1.14 * synchronization. This method may overestimate the
2755     * number of running threads.
2756 jsr166 1.1 *
2757     * @return the number of worker threads
2758     */
2759     public int getRunningThreadCount() {
2760 dl 1.78 int rc = 0;
2761     WorkQueue[] ws; WorkQueue w;
2762     if ((ws = workQueues) != null) {
2763 dl 1.86 for (int i = 1; i < ws.length; i += 2) {
2764     if ((w = ws[i]) != null && w.isApparentlyUnblocked())
2765 dl 1.78 ++rc;
2766     }
2767     }
2768     return rc;
2769 jsr166 1.1 }
2770    
2771     /**
2772     * Returns an estimate of the number of threads that are currently
2773     * stealing or executing tasks. This method may overestimate the
2774     * number of active threads.
2775     *
2776     * @return the number of active threads
2777     */
2778     public int getActiveThreadCount() {
2779 dl 1.200 int r = (config & SMASK) + (int)(ctl >> AC_SHIFT);
2780 jsr166 1.63 return (r <= 0) ? 0 : r; // suppress momentarily negative values
2781 jsr166 1.1 }
2782    
2783     /**
2784 jsr166 1.4 * Returns {@code true} if all worker threads are currently idle.
2785     * An idle worker is one that cannot obtain a task to execute
2786     * because none are available to steal from other threads, and
2787     * there are no pending submissions to the pool. This method is
2788     * conservative; it might not return {@code true} immediately upon
2789     * idleness of all threads, but will eventually become true if
2790     * threads remain inactive.
2791 jsr166 1.1 *
2792 jsr166 1.4 * @return {@code true} if all threads are currently idle
2793 jsr166 1.1 */
2794     public boolean isQuiescent() {
2795 dl 1.200 return (config & SMASK) + (int)(ctl >> AC_SHIFT) <= 0;
2796 jsr166 1.1 }
2797    
2798     /**
2799     * Returns an estimate of the total number of tasks stolen from
2800     * one thread's work queue by another. The reported value
2801     * underestimates the actual total number of steals when the pool
2802     * is not quiescent. This value may be useful for monitoring and
2803     * tuning fork/join programs: in general, steal counts should be
2804     * high enough to keep threads busy, but low enough to avoid
2805     * overhead and contention across threads.
2806     *
2807     * @return the number of steals
2808     */
2809     public long getStealCount() {
2810 dl 1.101 long count = stealCount;
2811 dl 1.78 WorkQueue[] ws; WorkQueue w;
2812     if ((ws = workQueues) != null) {
2813 dl 1.86 for (int i = 1; i < ws.length; i += 2) {
2814 dl 1.78 if ((w = ws[i]) != null)
2815 dl 1.105 count += w.nsteals;
2816 dl 1.78 }
2817     }
2818     return count;
2819 jsr166 1.1 }
2820    
2821     /**
2822     * Returns an estimate of the total number of tasks currently held
2823     * in queues by worker threads (but not including tasks submitted
2824     * to the pool that have not begun executing). This value is only
2825     * an approximation, obtained by iterating across all threads in
2826     * the pool. This method may be useful for tuning task
2827     * granularities.
2828     *
2829     * @return the number of queued tasks
2830     */
2831     public long getQueuedTaskCount() {
2832     long count = 0;
2833 dl 1.78 WorkQueue[] ws; WorkQueue w;
2834     if ((ws = workQueues) != null) {
2835 dl 1.86 for (int i = 1; i < ws.length; i += 2) {
2836 dl 1.78 if ((w = ws[i]) != null)
2837     count += w.queueSize();
2838     }
2839 dl 1.52 }
2840 jsr166 1.1 return count;
2841     }
2842    
2843     /**
2844 jsr166 1.8 * Returns an estimate of the number of tasks submitted to this
2845 dl 1.55 * pool that have not yet begun executing. This method may take
2846 dl 1.52 * time proportional to the number of submissions.
2847 jsr166 1.1 *
2848     * @return the number of queued submissions
2849     */
2850     public int getQueuedSubmissionCount() {
2851 dl 1.78 int count = 0;
2852     WorkQueue[] ws; WorkQueue w;
2853     if ((ws = workQueues) != null) {
2854 dl 1.86 for (int i = 0; i < ws.length; i += 2) {
2855 dl 1.78 if ((w = ws[i]) != null)
2856     count += w.queueSize();
2857     }
2858     }
2859     return count;
2860 jsr166 1.1 }
2861    
2862     /**
2863 jsr166 1.4 * Returns {@code true} if there are any tasks submitted to this
2864     * pool that have not yet begun executing.
2865 jsr166 1.1 *
2866     * @return {@code true} if there are any queued submissions
2867     */
2868     public boolean hasQueuedSubmissions() {
2869 dl 1.78 WorkQueue[] ws; WorkQueue w;
2870     if ((ws = workQueues) != null) {
2871 dl 1.86 for (int i = 0; i < ws.length; i += 2) {
2872 dl 1.115 if ((w = ws[i]) != null && !w.isEmpty())
2873 dl 1.78 return true;
2874     }
2875     }
2876     return false;
2877 jsr166 1.1 }
2878    
2879     /**
2880     * Removes and returns the next unexecuted submission if one is
2881     * available. This method may be useful in extensions to this
2882     * class that re-assign work in systems with multiple pools.
2883     *
2884 jsr166 1.4 * @return the next submission, or {@code null} if none
2885 jsr166 1.1 */
2886     protected ForkJoinTask<?> pollSubmission() {
2887 dl 1.78 WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2888     if ((ws = workQueues) != null) {
2889 dl 1.86 for (int i = 0; i < ws.length; i += 2) {
2890 dl 1.78 if ((w = ws[i]) != null && (t = w.poll()) != null)
2891     return t;
2892 dl 1.52 }
2893     }
2894     return null;
2895 jsr166 1.1 }
2896    
2897     /**
2898     * Removes all available unexecuted submitted and forked tasks
2899     * from scheduling queues and adds them to the given collection,
2900     * without altering their execution status. These may include
2901 jsr166 1.8 * artificially generated or wrapped tasks. This method is
2902     * designed to be invoked only when the pool is known to be
2903 jsr166 1.1 * quiescent. Invocations at other times may not remove all
2904     * tasks. A failure encountered while attempting to add elements
2905     * to collection {@code c} may result in elements being in
2906     * neither, either or both collections when the associated
2907     * exception is thrown. The behavior of this operation is
2908     * undefined if the specified collection is modified while the
2909     * operation is in progress.
2910     *
2911     * @param c the collection to transfer elements into
2912     * @return the number of elements transferred
2913     */
2914 jsr166 1.5 protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
2915 dl 1.52 int count = 0;
2916 dl 1.78 WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2917     if ((ws = workQueues) != null) {
2918 dl 1.86 for (int i = 0; i < ws.length; ++i) {
2919 dl 1.78 if ((w = ws[i]) != null) {
2920     while ((t = w.poll()) != null) {
2921     c.add(t);
2922     ++count;
2923     }
2924     }
2925 dl 1.52 }
2926     }
2927 dl 1.18 return count;
2928     }
2929    
2930     /**
2931 jsr166 1.1 * Returns a string identifying this pool, as well as its state,
2932     * including indications of run state, parallelism level, and
2933     * worker and task counts.
2934     *
2935     * @return a string identifying this pool, as well as its state
2936     */
2937     public String toString() {
2938 dl 1.86 // Use a single pass through workQueues to collect counts
2939     long qt = 0L, qs = 0L; int rc = 0;
2940 dl 1.101 long st = stealCount;
2941 dl 1.86 long c = ctl;
2942     WorkQueue[] ws; WorkQueue w;
2943     if ((ws = workQueues) != null) {
2944     for (int i = 0; i < ws.length; ++i) {
2945     if ((w = ws[i]) != null) {
2946     int size = w.queueSize();
2947     if ((i & 1) == 0)
2948     qs += size;
2949     else {
2950     qt += size;
2951 dl 1.105 st += w.nsteals;
2952 dl 1.86 if (w.isApparentlyUnblocked())
2953     ++rc;
2954     }
2955     }
2956     }
2957     }
2958 dl 1.200 int pc = (config & SMASK);
2959 dl 1.52 int tc = pc + (short)(c >>> TC_SHIFT);
2960 dl 1.78 int ac = pc + (int)(c >> AC_SHIFT);
2961     if (ac < 0) // ignore transient negative
2962     ac = 0;
2963 dl 1.200 int rs = runState;
2964     String level = ((rs & TERMINATED) != 0 ? "Terminated" :
2965     (rs & STOP) != 0 ? "Terminating" :
2966     (rs & SHUTDOWN) != 0 ? "Shutting down" :
2967     "Running");
2968 jsr166 1.1 return super.toString() +
2969 dl 1.52 "[" + level +
2970 dl 1.14 ", parallelism = " + pc +
2971     ", size = " + tc +
2972     ", active = " + ac +
2973     ", running = " + rc +
2974 jsr166 1.1 ", steals = " + st +
2975     ", tasks = " + qt +
2976     ", submissions = " + qs +
2977     "]";
2978     }
2979    
2980     /**
2981 dl 1.100 * Possibly initiates an orderly shutdown in which previously
2982     * submitted tasks are executed, but no new tasks will be
2983     * accepted. Invocation has no effect on execution state if this
2984 jsr166 1.137 * is the {@link #commonPool()}, and no additional effect if
2985 dl 1.100 * already shut down. Tasks that are in the process of being
2986     * submitted concurrently during the course of this method may or
2987     * may not be rejected.
2988 jsr166 1.1 *
2989     * @throws SecurityException if a security manager exists and
2990     * the caller is not permitted to modify threads
2991     * because it does not hold {@link
2992     * java.lang.RuntimePermission}{@code ("modifyThread")}
2993     */
2994     public void shutdown() {
2995     checkPermission();
2996 dl 1.105 tryTerminate(false, true);
2997 jsr166 1.1 }
2998    
2999     /**
3000 dl 1.100 * Possibly attempts to cancel and/or stop all tasks, and reject
3001     * all subsequently submitted tasks. Invocation has no effect on
3002 jsr166 1.137 * execution state if this is the {@link #commonPool()}, and no
3003 dl 1.100 * additional effect if already shut down. Otherwise, tasks that
3004     * are in the process of being submitted or executed concurrently
3005     * during the course of this method may or may not be
3006     * rejected. This method cancels both existing and unexecuted
3007     * tasks, in order to permit termination in the presence of task
3008     * dependencies. So the method always returns an empty list
3009     * (unlike the case for some other Executors).
3010 jsr166 1.1 *
3011     * @return an empty list
3012     * @throws SecurityException if a security manager exists and
3013     * the caller is not permitted to modify threads
3014     * because it does not hold {@link
3015     * java.lang.RuntimePermission}{@code ("modifyThread")}
3016     */
3017     public List<Runnable> shutdownNow() {
3018     checkPermission();
3019 dl 1.105 tryTerminate(true, true);
3020 jsr166 1.1 return Collections.emptyList();
3021     }
3022    
3023     /**
3024     * Returns {@code true} if all tasks have completed following shut down.
3025     *
3026     * @return {@code true} if all tasks have completed following shut down
3027     */
3028     public boolean isTerminated() {
3029 dl 1.200 return (runState & TERMINATED) != 0;
3030 jsr166 1.1 }
3031    
3032     /**
3033     * Returns {@code true} if the process of termination has
3034 jsr166 1.9 * commenced but not yet completed. This method may be useful for
3035     * debugging. A return of {@code true} reported a sufficient
3036     * period after shutdown may indicate that submitted tasks have
3037 jsr166 1.119 * ignored or suppressed interruption, or are waiting for I/O,
3038 dl 1.49 * causing this executor not to properly terminate. (See the
3039     * advisory notes for class {@link ForkJoinTask} stating that
3040     * tasks should not normally entail blocking operations. But if
3041     * they do, they must abort them on interrupt.)
3042 jsr166 1.1 *
3043 jsr166 1.9 * @return {@code true} if terminating but not yet terminated
3044 jsr166 1.1 */
3045     public boolean isTerminating() {
3046 dl 1.200 int rs = runState;
3047     return (rs & STOP) != 0 && (rs & TERMINATED) == 0;
3048 jsr166 1.1 }
3049    
3050     /**
3051     * Returns {@code true} if this pool has been shut down.
3052     *
3053     * @return {@code true} if this pool has been shut down
3054     */
3055     public boolean isShutdown() {
3056 dl 1.200 return (runState & SHUTDOWN) != 0;
3057 jsr166 1.9 }
3058    
3059     /**
3060 dl 1.105 * Blocks until all tasks have completed execution after a
3061     * shutdown request, or the timeout occurs, or the current thread
3062 dl 1.134 * is interrupted, whichever happens first. Because the {@link
3063     * #commonPool()} never terminates until program shutdown, when
3064     * applied to the common pool, this method is equivalent to {@link
3065 jsr166 1.158 * #awaitQuiescence(long, TimeUnit)} but always returns {@code false}.
3066 jsr166 1.1 *
3067     * @param timeout the maximum time to wait
3068     * @param unit the time unit of the timeout argument
3069     * @return {@code true} if this executor terminated and
3070     * {@code false} if the timeout elapsed before termination
3071     * @throws InterruptedException if interrupted while waiting
3072     */
3073     public boolean awaitTermination(long timeout, TimeUnit unit)
3074     throws InterruptedException {
3075 dl 1.134 if (Thread.interrupted())
3076     throw new InterruptedException();
3077     if (this == common) {
3078     awaitQuiescence(timeout, unit);
3079     return false;
3080     }
3081 dl 1.52 long nanos = unit.toNanos(timeout);
3082 dl 1.101 if (isTerminated())
3083     return true;
3084 dl 1.183 if (nanos <= 0L)
3085     return false;
3086     long deadline = System.nanoTime() + nanos;
3087 jsr166 1.103 synchronized (this) {
3088 jsr166 1.184 for (;;) {
3089 dl 1.183 if (isTerminated())
3090     return true;
3091     if (nanos <= 0L)
3092     return false;
3093     long millis = TimeUnit.NANOSECONDS.toMillis(nanos);
3094     wait(millis > 0L ? millis : 1L);
3095     nanos = deadline - System.nanoTime();
3096 dl 1.52 }
3097 dl 1.18 }
3098 jsr166 1.1 }
3099    
3100     /**
3101 dl 1.134 * If called by a ForkJoinTask operating in this pool, equivalent
3102     * in effect to {@link ForkJoinTask#helpQuiesce}. Otherwise,
3103     * waits and/or attempts to assist performing tasks until this
3104     * pool {@link #isQuiescent} or the indicated timeout elapses.
3105     *
3106     * @param timeout the maximum time to wait
3107     * @param unit the time unit of the timeout argument
3108     * @return {@code true} if quiescent; {@code false} if the
3109     * timeout elapsed.
3110     */
3111     public boolean awaitQuiescence(long timeout, TimeUnit unit) {
3112     long nanos = unit.toNanos(timeout);
3113     ForkJoinWorkerThread wt;
3114     Thread thread = Thread.currentThread();
3115     if ((thread instanceof ForkJoinWorkerThread) &&
3116     (wt = (ForkJoinWorkerThread)thread).pool == this) {
3117     helpQuiescePool(wt.workQueue);
3118     return true;
3119     }
3120     long startTime = System.nanoTime();
3121     WorkQueue[] ws;
3122     int r = 0, m;
3123     boolean found = true;
3124     while (!isQuiescent() && (ws = workQueues) != null &&
3125     (m = ws.length - 1) >= 0) {
3126     if (!found) {
3127     if ((System.nanoTime() - startTime) > nanos)
3128     return false;
3129     Thread.yield(); // cannot block
3130     }
3131     found = false;
3132     for (int j = (m + 1) << 2; j >= 0; --j) {
3133 dl 1.200 ForkJoinTask<?> t; WorkQueue q; int b, k;
3134     if ((k = r++ & m) <= m && k >= 0 && (q = ws[k]) != null &&
3135     (b = q.base) - q.top < 0) {
3136 dl 1.134 found = true;
3137 dl 1.172 if ((t = q.pollAt(b)) != null)
3138 dl 1.134 t.doExec();
3139     break;
3140     }
3141     }
3142     }
3143     return true;
3144     }
3145    
3146     /**
3147     * Waits and/or attempts to assist performing tasks indefinitely
3148 jsr166 1.141 * until the {@link #commonPool()} {@link #isQuiescent}.
3149 dl 1.134 */
3150 dl 1.136 static void quiesceCommonPool() {
3151 dl 1.134 common.awaitQuiescence(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
3152     }
3153    
3154     /**
3155 jsr166 1.1 * Interface for extending managed parallelism for tasks running
3156 jsr166 1.8 * in {@link ForkJoinPool}s.
3157     *
3158 dl 1.19 * <p>A {@code ManagedBlocker} provides two methods. Method
3159     * {@code isReleasable} must return {@code true} if blocking is
3160     * not necessary. Method {@code block} blocks the current thread
3161     * if necessary (perhaps internally invoking {@code isReleasable}
3162 dl 1.54 * before actually blocking). These actions are performed by any
3163 jsr166 1.157 * thread invoking {@link ForkJoinPool#managedBlock(ManagedBlocker)}.
3164     * The unusual methods in this API accommodate synchronizers that
3165     * may, but don't usually, block for long periods. Similarly, they
3166 dl 1.54 * allow more efficient internal handling of cases in which
3167     * additional workers may be, but usually are not, needed to
3168     * ensure sufficient parallelism. Toward this end,
3169     * implementations of method {@code isReleasable} must be amenable
3170     * to repeated invocation.
3171 jsr166 1.1 *
3172     * <p>For example, here is a ManagedBlocker based on a
3173     * ReentrantLock:
3174     * <pre> {@code
3175     * class ManagedLocker implements ManagedBlocker {
3176     * final ReentrantLock lock;
3177     * boolean hasLock = false;
3178     * ManagedLocker(ReentrantLock lock) { this.lock = lock; }
3179     * public boolean block() {
3180     * if (!hasLock)
3181     * lock.lock();
3182     * return true;
3183     * }
3184     * public boolean isReleasable() {
3185     * return hasLock || (hasLock = lock.tryLock());
3186     * }
3187     * }}</pre>
3188 dl 1.19 *
3189     * <p>Here is a class that possibly blocks waiting for an
3190     * item on a given queue:
3191     * <pre> {@code
3192     * class QueueTaker<E> implements ManagedBlocker {
3193     * final BlockingQueue<E> queue;
3194     * volatile E item = null;
3195     * QueueTaker(BlockingQueue<E> q) { this.queue = q; }
3196     * public boolean block() throws InterruptedException {
3197     * if (item == null)
3198 dl 1.23 * item = queue.take();
3199 dl 1.19 * return true;
3200     * }
3201     * public boolean isReleasable() {
3202 dl 1.23 * return item != null || (item = queue.poll()) != null;
3203 dl 1.19 * }
3204     * public E getItem() { // call after pool.managedBlock completes
3205     * return item;
3206     * }
3207     * }}</pre>
3208 jsr166 1.1 */
3209     public static interface ManagedBlocker {
3210     /**
3211     * Possibly blocks the current thread, for example waiting for
3212     * a lock or condition.
3213     *
3214 jsr166 1.4 * @return {@code true} if no additional blocking is necessary
3215     * (i.e., if isReleasable would return true)
3216 jsr166 1.1 * @throws InterruptedException if interrupted while waiting
3217     * (the method is not required to do so, but is allowed to)
3218     */
3219     boolean block() throws InterruptedException;
3220    
3221     /**
3222 jsr166 1.4 * Returns {@code true} if blocking is unnecessary.
3223 jsr166 1.154 * @return {@code true} if blocking is unnecessary
3224 jsr166 1.1 */
3225     boolean isReleasable();
3226     }
3227    
3228     /**
3229     * Blocks in accord with the given blocker. If the current thread
3230 jsr166 1.8 * is a {@link ForkJoinWorkerThread}, this method possibly
3231     * arranges for a spare thread to be activated if necessary to
3232 dl 1.18 * ensure sufficient parallelism while the current thread is blocked.
3233 jsr166 1.1 *
3234 jsr166 1.8 * <p>If the caller is not a {@link ForkJoinTask}, this method is
3235     * behaviorally equivalent to
3236 jsr166 1.82 * <pre> {@code
3237 jsr166 1.1 * while (!blocker.isReleasable())
3238     * if (blocker.block())
3239 jsr166 1.196 * return;}</pre>
3240 jsr166 1.8 *
3241     * If the caller is a {@code ForkJoinTask}, then the pool may
3242     * first be expanded to ensure parallelism, and later adjusted.
3243 jsr166 1.1 *
3244     * @param blocker the blocker
3245     * @throws InterruptedException if blocker.block did so
3246     */
3247 dl 1.18 public static void managedBlock(ManagedBlocker blocker)
3248 jsr166 1.1 throws InterruptedException {
3249 dl 1.200 ForkJoinPool p;
3250     ForkJoinWorkerThread wt;
3251 jsr166 1.1 Thread t = Thread.currentThread();
3252 dl 1.200 if ((t instanceof ForkJoinWorkerThread) &&
3253     (p = (wt = (ForkJoinWorkerThread)t).pool) != null) {
3254     WorkQueue w = wt.workQueue;
3255 dl 1.172 while (!blocker.isReleasable()) {
3256 dl 1.200 if (p.tryCompensate(w)) {
3257 dl 1.105 try {
3258     do {} while (!blocker.isReleasable() &&
3259     !blocker.block());
3260     } finally {
3261 dl 1.200 U.getAndAddLong(p, CTL, AC_UNIT);
3262 dl 1.105 }
3263     break;
3264 dl 1.78 }
3265     }
3266 dl 1.18 }
3267 dl 1.105 else {
3268     do {} while (!blocker.isReleasable() &&
3269     !blocker.block());
3270     }
3271 jsr166 1.1 }
3272    
3273 jsr166 1.7 // AbstractExecutorService overrides. These rely on undocumented
3274     // fact that ForkJoinTask.adapt returns ForkJoinTasks that also
3275     // implement RunnableFuture.
3276 jsr166 1.1
3277     protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
3278 dl 1.90 return new ForkJoinTask.AdaptedRunnable<T>(runnable, value);
3279 jsr166 1.1 }
3280    
3281     protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
3282 dl 1.90 return new ForkJoinTask.AdaptedCallable<T>(callable);
3283 jsr166 1.1 }
3284    
3285     // Unsafe mechanics
3286 dl 1.78 private static final sun.misc.Unsafe U;
3287 dl 1.200 private static final int ABASE;
3288     private static final int ASHIFT;
3289 dl 1.78 private static final long CTL;
3290 dl 1.211 private static final long RUNSTATE;
3291     private static final long STEALCOUNT;
3292 dl 1.78 private static final long PARKBLOCKER;
3293 dl 1.211 private static final long QBASE; // these must be same as in WorkQueue
3294 dl 1.200 private static final long QTOP;
3295 dl 1.105 private static final long QLOCK;
3296 dl 1.200 private static final long QSCANSTATE;
3297     private static final long QPARKER;
3298     private static final long QCURRENTSTEAL;
3299     private static final long QCURRENTJOIN;
3300 dl 1.52
3301     static {
3302 jsr166 1.142 // initialize field offsets for CAS etc
3303 jsr166 1.3 try {
3304 dl 1.78 U = sun.misc.Unsafe.getUnsafe();
3305 jsr166 1.64 Class<?> k = ForkJoinPool.class;
3306 dl 1.78 CTL = U.objectFieldOffset
3307 dl 1.52 (k.getDeclaredField("ctl"));
3308 dl 1.211 RUNSTATE = U.objectFieldOffset
3309     (k.getDeclaredField("runState"));
3310 dl 1.101 STEALCOUNT = U.objectFieldOffset
3311     (k.getDeclaredField("stealCount"));
3312 dl 1.86 Class<?> tk = Thread.class;
3313 dl 1.78 PARKBLOCKER = U.objectFieldOffset
3314     (tk.getDeclaredField("parkBlocker"));
3315 dl 1.105 Class<?> wk = WorkQueue.class;
3316 dl 1.170 QBASE = U.objectFieldOffset
3317     (wk.getDeclaredField("base"));
3318 dl 1.200 QTOP = U.objectFieldOffset
3319     (wk.getDeclaredField("top"));
3320 dl 1.105 QLOCK = U.objectFieldOffset
3321     (wk.getDeclaredField("qlock"));
3322 dl 1.200 QSCANSTATE = U.objectFieldOffset
3323     (wk.getDeclaredField("scanState"));
3324     QPARKER = U.objectFieldOffset
3325     (wk.getDeclaredField("parker"));
3326     QCURRENTSTEAL = U.objectFieldOffset
3327     (wk.getDeclaredField("currentSteal"));
3328     QCURRENTJOIN = U.objectFieldOffset
3329     (wk.getDeclaredField("currentJoin"));
3330 dl 1.105 Class<?> ak = ForkJoinTask[].class;
3331 dl 1.90 ABASE = U.arrayBaseOffset(ak);
3332 jsr166 1.142 int scale = U.arrayIndexScale(ak);
3333     if ((scale & (scale - 1)) != 0)
3334     throw new Error("data type scale not a power of two");
3335     ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
3336 dl 1.52 } catch (Exception e) {
3337     throw new Error(e);
3338     }
3339 dl 1.105
3340 dl 1.208 commonMaxSpares = DEFAULT_COMMON_MAX_SPARES;
3341 dl 1.152 defaultForkJoinWorkerThreadFactory =
3342 dl 1.112 new DefaultForkJoinWorkerThreadFactory();
3343 dl 1.115 modifyThreadPermission = new RuntimePermission("modifyThread");
3344    
3345 dl 1.152 common = java.security.AccessController.doPrivileged
3346     (new java.security.PrivilegedAction<ForkJoinPool>() {
3347     public ForkJoinPool run() { return makeCommonPool(); }});
3348 dl 1.200 int par = common.config & SMASK; // report 1 even if threads disabled
3349 dl 1.160 commonParallelism = par > 0 ? par : 1;
3350 dl 1.152 }
3351 dl 1.112
3352 dl 1.152 /**
3353     * Creates and returns the common pool, respecting user settings
3354     * specified via system properties.
3355     */
3356     private static ForkJoinPool makeCommonPool() {
3357 dl 1.160 int parallelism = -1;
3358 dl 1.197 ForkJoinWorkerThreadFactory factory = null;
3359 jsr166 1.156 UncaughtExceptionHandler handler = null;
3360 jsr166 1.189 try { // ignore exceptions in accessing/parsing properties
3361 dl 1.112 String pp = System.getProperty
3362     ("java.util.concurrent.ForkJoinPool.common.parallelism");
3363 dl 1.152 String fp = System.getProperty
3364     ("java.util.concurrent.ForkJoinPool.common.threadFactory");
3365 dl 1.112 String hp = System.getProperty
3366     ("java.util.concurrent.ForkJoinPool.common.exceptionHandler");
3367 dl 1.208 String mp = System.getProperty
3368     ("java.util.concurrent.ForkJoinPool.common.maximumSpares");
3369 dl 1.152 if (pp != null)
3370     parallelism = Integer.parseInt(pp);
3371 dl 1.112 if (fp != null)
3372 dl 1.152 factory = ((ForkJoinWorkerThreadFactory)ClassLoader.
3373     getSystemClassLoader().loadClass(fp).newInstance());
3374 dl 1.112 if (hp != null)
3375 jsr166 1.156 handler = ((UncaughtExceptionHandler)ClassLoader.
3376 dl 1.112 getSystemClassLoader().loadClass(hp).newInstance());
3377 dl 1.208 if (mp != null)
3378     commonMaxSpares = Integer.parseInt(mp);
3379 dl 1.112 } catch (Exception ignore) {
3380     }
3381 dl 1.197 if (factory == null) {
3382     if (System.getSecurityManager() == null)
3383     factory = defaultForkJoinWorkerThreadFactory;
3384     else // use security-managed default
3385     factory = new InnocuousForkJoinWorkerThreadFactory();
3386     }
3387 dl 1.167 if (parallelism < 0 && // default 1 less than #cores
3388 dl 1.193 (parallelism = Runtime.getRuntime().availableProcessors() - 1) <= 0)
3389     parallelism = 1;
3390 dl 1.152 if (parallelism > MAX_CAP)
3391     parallelism = MAX_CAP;
3392 dl 1.185 return new ForkJoinPool(parallelism, factory, handler, LIFO_QUEUE,
3393 dl 1.152 "ForkJoinPool.commonPool-worker-");
3394 jsr166 1.3 }
3395 dl 1.52
3396 dl 1.197 /**
3397     * Factory for innocuous worker threads
3398     */
3399     static final class InnocuousForkJoinWorkerThreadFactory
3400     implements ForkJoinWorkerThreadFactory {
3401    
3402     /**
3403     * An ACC to restrict permissions for the factory itself.
3404     * The constructed workers have no permissions set.
3405     */
3406     private static final AccessControlContext innocuousAcc;
3407     static {
3408     Permissions innocuousPerms = new Permissions();
3409     innocuousPerms.add(modifyThreadPermission);
3410     innocuousPerms.add(new RuntimePermission(
3411     "enableContextClassLoaderOverride"));
3412     innocuousPerms.add(new RuntimePermission(
3413     "modifyThreadGroup"));
3414     innocuousAcc = new AccessControlContext(new ProtectionDomain[] {
3415     new ProtectionDomain(null, innocuousPerms)
3416     });
3417     }
3418    
3419     public final ForkJoinWorkerThread newThread(ForkJoinPool pool) {
3420     return (ForkJoinWorkerThread.InnocuousForkJoinWorkerThread)
3421     java.security.AccessController.doPrivileged(
3422     new java.security.PrivilegedAction<ForkJoinWorkerThread>() {
3423     public ForkJoinWorkerThread run() {
3424     return new ForkJoinWorkerThread.
3425     InnocuousForkJoinWorkerThread(pool);
3426     }}, innocuousAcc);
3427     }
3428     }
3429    
3430 jsr166 1.1 }