ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.309
Committed: Sat Mar 26 15:18:22 2016 UTC (8 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.308: +1 -1 lines
Log Message:
whitespace

File Contents

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