ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.365
Committed: Mon Jan 20 15:51:54 2020 UTC (4 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.364: +32 -46 lines
Log Message:
improve compatibilty for timeouts etc; increase common code paths

File Contents

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