ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.318
Committed: Tue Jun 28 14:41:58 2016 UTC (7 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.317: +1 -1 lines
Log Message:
s/nonnull/non-null/

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