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