ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.307
Committed: Tue Mar 15 15:56:30 2016 UTC (8 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.306: +26 -20 lines
Log Message:
Use predicate for saturate control

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