ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinPool.java
Revision: 1.93
Committed: Wed Feb 23 12:48:43 2011 UTC (13 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.92: +58 -50 lines
Log Message:
Doc improvements; tolerate spurious wakeups when shrinking

File Contents

# User Rev Content
1 dl 1.1 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain, as explained at
4     * http://creativecommons.org/licenses/publicdomain
5     */
6    
7     package jsr166y;
8 jsr166 1.22
9     import java.util.ArrayList;
10     import java.util.Arrays;
11     import java.util.Collection;
12     import java.util.Collections;
13     import java.util.List;
14 dl 1.91 import java.util.Random;
15 dl 1.78 import java.util.concurrent.AbstractExecutorService;
16     import java.util.concurrent.Callable;
17     import java.util.concurrent.ExecutorService;
18     import java.util.concurrent.Future;
19     import java.util.concurrent.RejectedExecutionException;
20     import java.util.concurrent.RunnableFuture;
21     import java.util.concurrent.TimeUnit;
22     import java.util.concurrent.TimeoutException;
23     import java.util.concurrent.atomic.AtomicInteger;
24 jsr166 1.22 import java.util.concurrent.locks.LockSupport;
25     import java.util.concurrent.locks.ReentrantLock;
26 dl 1.91 import java.util.concurrent.locks.Condition;
27 dl 1.1
28     /**
29 jsr166 1.29 * An {@link ExecutorService} for running {@link ForkJoinTask}s.
30 jsr166 1.39 * A {@code ForkJoinPool} provides the entry point for submissions
31 dl 1.57 * from non-{@code ForkJoinTask} clients, as well as management and
32 jsr166 1.48 * monitoring operations.
33 dl 1.1 *
34 dl 1.42 * <p>A {@code ForkJoinPool} differs from other kinds of {@link
35     * ExecutorService} mainly by virtue of employing
36     * <em>work-stealing</em>: all threads in the pool attempt to find and
37     * execute subtasks created by other active tasks (eventually blocking
38     * waiting for work if none exist). This enables efficient processing
39     * when most tasks spawn other subtasks (as do most {@code
40 dl 1.57 * ForkJoinTask}s). When setting <em>asyncMode</em> to true in
41     * constructors, {@code ForkJoinPool}s may also be appropriate for use
42     * with event-style tasks that are never joined.
43 dl 1.1 *
44 dl 1.42 * <p>A {@code ForkJoinPool} is constructed with a given target
45     * parallelism level; by default, equal to the number of available
46 dl 1.57 * processors. The pool attempts to maintain enough active (or
47     * available) threads by dynamically adding, suspending, or resuming
48     * internal worker threads, even if some tasks are stalled waiting to
49     * join others. However, no such adjustments are guaranteed in the
50     * face of blocked IO or other unmanaged synchronization. The nested
51     * {@link ManagedBlocker} interface enables extension of the kinds of
52     * synchronization accommodated.
53 dl 1.1 *
54     * <p>In addition to execution and lifecycle control methods, this
55     * class provides status check methods (for example
56 jsr166 1.29 * {@link #getStealCount}) that are intended to aid in developing,
57 dl 1.1 * tuning, and monitoring fork/join applications. Also, method
58 jsr166 1.29 * {@link #toString} returns indications of pool state in a
59 dl 1.2 * convenient form for informal monitoring.
60 dl 1.1 *
61 dl 1.57 * <p> As is the case with other ExecutorServices, there are three
62 dl 1.60 * main task execution methods summarized in the following
63 dl 1.57 * table. These are designed to be used by clients not already engaged
64     * in fork/join computations in the current pool. The main forms of
65     * these methods accept instances of {@code ForkJoinTask}, but
66     * overloaded forms also allow mixed execution of plain {@code
67     * Runnable}- or {@code Callable}- based activities as well. However,
68     * tasks that are already executing in a pool should normally
69     * <em>NOT</em> use these pool execution methods, but instead use the
70 dl 1.59 * within-computation forms listed in the table.
71 dl 1.57 *
72     * <table BORDER CELLPADDING=3 CELLSPACING=1>
73     * <tr>
74     * <td></td>
75     * <td ALIGN=CENTER> <b>Call from non-fork/join clients</b></td>
76     * <td ALIGN=CENTER> <b>Call from within fork/join computations</b></td>
77     * </tr>
78     * <tr>
79 jsr166 1.67 * <td> <b>Arrange async execution</td>
80 dl 1.57 * <td> {@link #execute(ForkJoinTask)}</td>
81     * <td> {@link ForkJoinTask#fork}</td>
82     * </tr>
83     * <tr>
84     * <td> <b>Await and obtain result</td>
85     * <td> {@link #invoke(ForkJoinTask)}</td>
86     * <td> {@link ForkJoinTask#invoke}</td>
87     * </tr>
88     * <tr>
89     * <td> <b>Arrange exec and obtain Future</td>
90     * <td> {@link #submit(ForkJoinTask)}</td>
91     * <td> {@link ForkJoinTask#fork} (ForkJoinTasks <em>are</em> Futures)</td>
92     * </tr>
93     * </table>
94 dl 1.59 *
95 dl 1.42 * <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is
96     * used for all parallel task execution in a program or subsystem.
97     * Otherwise, use would not usually outweigh the construction and
98     * bookkeeping overhead of creating a large set of threads. For
99 jsr166 1.43 * example, a common pool could be used for the {@code SortTasks}
100 dl 1.42 * illustrated in {@link RecursiveAction}. Because {@code
101     * ForkJoinPool} uses threads in {@linkplain java.lang.Thread#isDaemon
102 jsr166 1.43 * daemon} mode, there is typically no need to explicitly {@link
103 dl 1.42 * #shutdown} such a pool upon program exit.
104     *
105     * <pre>
106     * static final ForkJoinPool mainPool = new ForkJoinPool();
107     * ...
108     * public void sort(long[] array) {
109     * mainPool.invoke(new SortTask(array, 0, array.length));
110     * }
111     * </pre>
112     *
113 dl 1.1 * <p><b>Implementation notes</b>: This implementation restricts the
114 dl 1.2 * maximum number of running threads to 32767. Attempts to create
115 jsr166 1.48 * pools with greater than the maximum number result in
116 jsr166 1.39 * {@code IllegalArgumentException}.
117 jsr166 1.16 *
118 jsr166 1.48 * <p>This implementation rejects submitted tasks (that is, by throwing
119 dl 1.58 * {@link RejectedExecutionException}) only when the pool is shut down
120 dl 1.62 * or internal resources have been exhausted.
121 jsr166 1.48 *
122 jsr166 1.16 * @since 1.7
123     * @author Doug Lea
124 dl 1.1 */
125 dl 1.2 public class ForkJoinPool extends AbstractExecutorService {
126 dl 1.1
127     /*
128 dl 1.53 * Implementation Overview
129     *
130     * This class provides the central bookkeeping and control for a
131     * set of worker threads: Submissions from non-FJ threads enter
132     * into a submission queue. Workers take these tasks and typically
133     * split them into subtasks that may be stolen by other workers.
134 dl 1.91 * Preference rules give first priority to processing tasks from
135     * their own queues (LIFO or FIFO, depending on mode), then to
136     * randomized FIFO steals of tasks in other worker queues, and
137     * lastly to new submissions.
138     *
139     * The main throughput advantages of work-stealing stem from
140     * decentralized control -- workers mostly take tasks from
141     * themselves or each other. We cannot negate this in the
142     * implementation of other management responsibilities. The main
143     * tactic for avoiding bottlenecks is packing nearly all
144     * essentially atomic control state into a single 64bit volatile
145     * variable ("ctl"). This variable is read on the order of 10-100
146     * times as often as it is modified (always via CAS). (There is
147     * some additional control state, for example variable "shutdown"
148     * for which we can cope with uncoordinated updates.) This
149     * streamlines synchronization and control at the expense of messy
150     * constructions needed to repack status bits upon updates.
151     * Updates tend not to contend with each other except during
152     * bursts while submitted tasks begin or end. In some cases when
153     * they do contend, threads can instead do something else
154     * (usually, scan for tesks) until contention subsides.
155     *
156     * To enable packing, we restrict maximum parallelism to (1<<15)-1
157     * (which is far in excess of normal operating range) to allow
158     * ids, counts, and their negations (used for thresholding) to fit
159     * into 16bit fields.
160     *
161     * Recording Workers. Workers are recorded in the "workers" array
162     * that is created upon pool construction and expanded if (rarely)
163     * necessary. This is an array as opposed to some other data
164     * structure to support index-based random steals by workers.
165     * Updates to the array recording new workers and unrecording
166     * terminated ones are protected from each other by a seqLock
167     * (scanGuard) but the array is otherwise concurrently readable,
168     * and accessed directly by workers. To simplify index-based
169     * operations, the array size is always a power of two, and all
170     * readers must tolerate null slots. To avoid flailing during
171     * start-up, the array is presized to hold twice #parallelism
172     * workers (which is unlikely to need further resizing during
173     * execution). But to avoid dealing with so many null slots,
174     * variable scanGuard includes a mask for the nearest power of two
175     * that contains all current workers. All worker thread creation
176     * is on-demand, triggered by task submissions, replacement of
177     * terminated workers, and/or compensation for blocked
178     * workers. However, all other support code is set up to work with
179     * other policies. To ensure that we do not hold on to worker
180     * references that would prevent GC, ALL accesses to workers are
181     * via indices into the workers array (which is one source of some
182     * of the messy code constructions here). In essence, the workers
183     * array serves as a weak reference mechanism. Thus for example
184     * the wait queue field of ctl stores worker indices, not worker
185     * references. Access to the workers in associated methods (for
186     * example signalWork) must both index-check and null-check the
187     * IDs. All such accesses ignore bad IDs by returning out early
188     * from what they are doing, since this can only be associated
189     * with termination, in which case it is OK to give up.
190     *
191     * All uses of the workers array, as well as queue arrays, check
192     * that the array is non-null (even if previously non-null). This
193     * allows nulling during termination, which is currently not
194     * necessary, but remains an option for resource-revocation-based
195     * shutdown schemes.
196     *
197     * Wait Queuing. Unlike HPC work-stealing frameworks, we cannot
198     * let workers spin indefinitely scanning for tasks when none are
199     * can be immediately found, and we cannot start/resume workers
200     * unless there appear to be tasks available. On the other hand,
201     * we must quickly prod them into action when new tasks are
202     * submitted or generated. We park/unpark workers after placing
203     * in an event wait queue when they cannot find work. This "queue"
204     * is actually a simple Treiber stack, headed by the "id" field of
205     * ctl, plus a 15bit counter value to both wake up waiters (by
206     * advancing their count) and avoid ABA effects. Successors are
207     * held in worker field "nextWait". Queuing deals with several
208     * intrinsic races, mainly that a task-producing thread can miss
209     * seeing (and signalling) another thread that gave up looking for
210     * work but has not yet entered the wait queue. We solve this by
211     * requiring a full sweep of all workers both before (in scan())
212     * and after (in awaitWork()) a newly waiting worker is added to
213     * the wait queue. During a rescan, the worker might release some
214     * other queued worker rather than itself, which has the same net
215     * effect.
216     *
217     * Signalling. We create or wake up workers only when there
218     * appears to be at least one task they might be able to find and
219     * execute. When a submission is added or another worker adds a
220     * task to a queue that previously had two or fewer tasks, they
221     * signal waiting workers (or trigger creation of new ones if
222     * fewer than the given parallelism level -- see signalWork).
223     * These primary signals are buttressed by signals during rescans
224     * as well as those performed when a worker steals a task and
225     * notices that there are more tasks too; together these cover the
226     * signals needed in cases when more than two tasks are pushed
227     * but untaken.
228     *
229     * Trimming workers. To release resources after periods of lack of
230     * use, a worker starting to wait when the pool is quiescent will
231     * time out and terminate if the pool has remained quiescent for
232     * SHRINK_RATE nanosecs.
233     *
234     * Submissions. External submissions are maintained in an
235     * array-based queue that is structured identically to
236     * ForkJoinWorkerThread queues (which see) except for the use of
237     * submissionLock in method addSubmission. Unlike worker queues,
238     * multiple external threads can add new submissions.
239     *
240     * Compensation. Beyond work-stealing support and lifecycle
241     * control, the main responsibility of this framework is to take
242     * actions when one worker is waiting to join a task stolen (or
243     * always held by) another. Because we are multiplexing many
244     * tasks on to a pool of workers, we can't just let them block (as
245     * in Thread.join). We also cannot just reassign the joiner's
246     * run-time stack with another and replace it later, which would
247     * be a form of "continuation", that even if possible is not
248     * necessarily a good idea since we sometimes need both an
249     * unblocked task and its continuation to progress. Instead we
250 dl 1.60 * combine two tactics:
251 dl 1.58 *
252 dl 1.60 * Helping: Arranging for the joiner to execute some task that it
253 dl 1.58 * would be running if the steal had not occurred. Method
254 dl 1.91 * ForkJoinWorkerThread.joinTask tracks joining->stealing
255 dl 1.58 * links to try to find such a task.
256     *
257 dl 1.61 * Compensating: Unless there are already enough live threads,
258 dl 1.91 * method tryPreBlock() may create or re-activate a spare
259     * thread to compensate for blocked joiners until they
260     * unblock.
261     *
262     * The ManagedBlocker extension API can't use helping so relies
263     * only on compensation in method awaitBlocker.
264 dl 1.58 *
265 dl 1.91 * It is impossible to keep exactly the target parallelism number
266     * of threads running at any given time. Determining the
267 dl 1.66 * existence of conservatively safe helping targets, the
268     * availability of already-created spares, and the apparent need
269     * to create new spares are all racy and require heuristic
270 dl 1.91 * guidance, so we rely on multiple retries of each. Currently,
271     * in keeping with on-demand signalling policy, we compensate only
272     * if blocking would leave less than one active (non-waiting,
273     * non-blocked) worker. Additionally, to avoid some false alarms
274     * due to GC, lagging counters, system activity, etc, compensated
275     * blocking for joins is only attempted after a number of rechecks
276     * proportional to the current apparent deficit (where retries are
277     * interspersed with Thread.yield, for good citizenship). The
278     * variable blockedCount, incremented before blocking and
279     * decremented after, is sometimes needed to distinguish cases of
280     * waiting for work vs blocking on joins or other managed sync,
281     * but both the cases are equivalent for most pool control, so we
282     * can update non-atomically. (Additionally, contention on
283     * blockedCount alleviates some contention on ctl).
284     *
285     * Shutdown and Termination. A call to shutdownNow atomically sets
286     * the ctl stop bit and then (non-atomically) sets each workers
287     * "terminate" status, cancels all unprocessed tasks, and wakes up
288     * all waiting workers. Detecting whether termination should
289     * commence after a non-abrupt shutdown() call requires more work
290     * and bookkeeping. We need consensus about quiesence (i.e., that
291     * there is no more work) which is reflected in active counts so
292     * long as there are no current blockers, as well as possible
293     * re-evaluations during independent changes in blocking or
294     * quiescing workers.
295 dl 1.58 *
296 dl 1.91 * Style notes: There is a lot of representation-level coupling
297 dl 1.53 * among classes ForkJoinPool, ForkJoinWorkerThread, and
298 dl 1.91 * ForkJoinTask. Most fields of ForkJoinWorkerThread maintain
299     * data structures managed by ForkJoinPool, so are directly
300     * accessed. Conversely we allow access to "workers" array by
301 dl 1.53 * workers, and direct access to ForkJoinTask.status by both
302     * ForkJoinPool and ForkJoinWorkerThread. There is little point
303     * trying to reduce this, since any associated future changes in
304     * representations will need to be accompanied by algorithmic
305 dl 1.91 * changes anyway. All together, these low-level implementation
306     * choices produce as much as a factor of 4 performance
307     * improvement compared to naive implementations, and enable the
308     * processing of billions of tasks per second, at the expense of
309     * some ugliness.
310     *
311     * Methods signalWork() and scan() are the main bottlenecks so are
312     * especially heavily micro-optimized/mangled. There are lots of
313     * inline assignments (of form "while ((local = field) != 0)")
314     * which are usually the simplest way to ensure the required read
315     * orderings (which are sometimes critical). This leads to a
316     * "C"-like style of listing declarations of these locals at the
317     * heads of methods or blocks. There are several occurrences of
318     * the unusual "do {} while (!cas...)" which is the simplest way
319     * to force an update of a CAS'ed variable. There are also other
320     * coding oddities that help some methods perform reasonably even
321     * when interpreted (not compiled).
322     *
323     * The order of declarations in this file is: (1) declarations of
324     * statics (2) fields (along with constants used when unpacking
325     * some of them), listed in an order that tends to reduce
326     * contention among them a bit under most JVMs. (3) internal
327     * control methods (4) callbacks and other support for
328     * ForkJoinTask and ForkJoinWorkerThread classes, (5) exported
329     * methods (plus a few little helpers). (6) static block
330     * initializing all statics in a minimally dependent order.
331 dl 1.1 */
332    
333     /**
334 jsr166 1.35 * Factory for creating new {@link ForkJoinWorkerThread}s.
335     * A {@code ForkJoinWorkerThreadFactory} must be defined and used
336     * for {@code ForkJoinWorkerThread} subclasses that extend base
337     * functionality or initialize threads with different contexts.
338 dl 1.1 */
339     public static interface ForkJoinWorkerThreadFactory {
340     /**
341     * Returns a new worker thread operating in the given pool.
342     *
343     * @param pool the pool this thread works in
344 jsr166 1.48 * @throws NullPointerException if the pool is null
345 dl 1.1 */
346     public ForkJoinWorkerThread newThread(ForkJoinPool pool);
347     }
348    
349     /**
350 jsr166 1.17 * Default ForkJoinWorkerThreadFactory implementation; creates a
351 dl 1.1 * new ForkJoinWorkerThread.
352     */
353 dl 1.57 static class DefaultForkJoinWorkerThreadFactory
354 dl 1.1 implements ForkJoinWorkerThreadFactory {
355     public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
356 dl 1.53 return new ForkJoinWorkerThread(pool);
357 dl 1.1 }
358     }
359    
360     /**
361 dl 1.2 * Creates a new ForkJoinWorkerThread. This factory is used unless
362     * overridden in ForkJoinPool constructors.
363 dl 1.1 */
364 dl 1.2 public static final ForkJoinWorkerThreadFactory
365 dl 1.91 defaultForkJoinWorkerThreadFactory;
366 dl 1.1
367     /**
368     * Permission required for callers of methods that may start or
369     * kill threads.
370     */
371 dl 1.91 private static final RuntimePermission modifyThreadPermission;
372 dl 1.1
373     /**
374     * If there is a security manager, makes sure caller has
375     * permission to modify threads.
376     */
377     private static void checkPermission() {
378     SecurityManager security = System.getSecurityManager();
379     if (security != null)
380     security.checkPermission(modifyThreadPermission);
381     }
382    
383     /**
384     * Generator for assigning sequence numbers as pool names.
385     */
386 dl 1.91 private static final AtomicInteger poolNumberGenerator;
387 dl 1.1
388     /**
389 dl 1.91 * Generator for initial random seeds for worker victim
390     * selection. This is used only to create initial seeds. Random
391     * steals use a cheaper xorshift generator per steal attempt. We
392     * don't expect much contention on seedGenerator, so just use a
393     * plain Random.
394 dl 1.66 */
395 dl 1.91 static final Random workerSeedGenerator;
396 dl 1.66
397     /**
398 dl 1.91 * Array holding all worker threads in the pool. Initialized upon
399     * construction. Array size must be a power of two. Updates and
400     * replacements are protected by scanGuard, but the array is
401     * always kept in a consistent enough state to be randomly
402     * accessed without locking by workers performing work-stealing,
403     * as well as other traversal-based methods in this class, so long
404     * as reads memory-acquire by first reading ctl. All readers must
405     * tolerate that some array slots may be null.
406 dl 1.64 */
407 dl 1.91 ForkJoinWorkerThread[] workers;
408 dl 1.64
409     /**
410 dl 1.91 * Initial size for submission queue array. Must be a power of
411     * two. In many applications, these always stay small so we use a
412     * small initial cap.
413 dl 1.53 */
414 dl 1.91 private static final int INITIAL_QUEUE_CAPACITY = 8;
415 dl 1.53
416     /**
417 dl 1.91 * Maximum size for submission queue array. Must be a power of two
418     * less than or equal to 1 << (31 - width of array entry) to
419     * ensure lack of index wraparound, but is capped at a lower
420     * value to help users trap runaway computations.
421 dl 1.1 */
422 dl 1.91 private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 24; // 16M
423 dl 1.1
424     /**
425 dl 1.91 * Array serving as submission queue. Initialized upon construction.
426 dl 1.1 */
427 dl 1.91 private ForkJoinTask<?>[] submissionQueue;
428 dl 1.1
429     /**
430 dl 1.91 * Lock protecting submissions array for addSubmission
431 dl 1.1 */
432 dl 1.91 private final ReentrantLock submissionLock;
433 dl 1.1
434     /**
435 dl 1.91 * Condition for awaitTermination, using submissionLock for
436     * convenience.
437 dl 1.1 */
438 dl 1.91 private final Condition termination;
439 dl 1.1
440     /**
441     * Creation factory for worker threads.
442     */
443     private final ForkJoinWorkerThreadFactory factory;
444    
445     /**
446 dl 1.91 * The uncaught exception handler used when any worker abruptly
447     * terminates.
448 dl 1.1 */
449 dl 1.91 final Thread.UncaughtExceptionHandler ueh;
450 dl 1.1
451     /**
452 dl 1.91 * Prefix for assigning names to worker threads
453 dl 1.1 */
454 dl 1.91 private final String workerNamePrefix;
455 dl 1.53
456 dl 1.91 /**
457     * Sum of per-thread steal counts, updated only when threads are
458     * idle or terminating.
459     */
460     private volatile long stealCount;
461 dl 1.1
462     /**
463 dl 1.91 * Main pool control -- a long packed with:
464     * AC: Number of active running workers minus target parallelism (16 bits)
465     * TC: Number of total workers minus target parallelism (16bits)
466     * ST: true if pool is terminating (1 bit)
467     * EC: the wait count of top waiting thread (15 bits)
468     * ID: ~poolIndex of top of Treiber stack of waiting threads (16 bits)
469     *
470     * When convenient, we can extract the upper 32 bits of counts and
471     * the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e =
472     * (int)ctl. The ec field is never accessed alone, but always
473     * together with id and st. The offsets of counts by the target
474     * parallelism and the positionings of fields makes it possible to
475     * perform the most common checks via sign tests of fields: When
476     * ac is negative, there are not enough active workers, when tc is
477     * negative, there are not enough total workers, when id is
478     * negative, there is at least one waiting worker, and when e is
479     * negative, the pool is terminating. To deal with these possibly
480     * negative fields, we use casts in and out of "short" and/or
481     * signed shifts to maintain signedness. Note: AC_SHIFT is
482     * redundantly declared in ForkJoinWorkerThread in order to
483     * integrate a surplus-threads check.
484     */
485     volatile long ctl;
486    
487     // bit positions/shifts for fields
488     private static final int AC_SHIFT = 48;
489     private static final int TC_SHIFT = 32;
490     private static final int ST_SHIFT = 31;
491     private static final int EC_SHIFT = 16;
492    
493     // bounds
494     private static final int MAX_ID = 0x7fff; // max poolIndex
495     private static final int SMASK = 0xffff; // mask short bits
496     private static final int SHORT_SIGN = 1 << 15;
497     private static final int INT_SIGN = 1 << 31;
498    
499     // masks
500     private static final long STOP_BIT = 0x0001L << ST_SHIFT;
501     private static final long AC_MASK = ((long)SMASK) << AC_SHIFT;
502     private static final long TC_MASK = ((long)SMASK) << TC_SHIFT;
503    
504     // units for incrementing and decrementing
505     private static final long TC_UNIT = 1L << TC_SHIFT;
506     private static final long AC_UNIT = 1L << AC_SHIFT;
507    
508     // masks and units for dealing with u = (int)(ctl >>> 32)
509     private static final int UAC_SHIFT = AC_SHIFT - 32;
510     private static final int UTC_SHIFT = TC_SHIFT - 32;
511     private static final int UAC_MASK = SMASK << UAC_SHIFT;
512     private static final int UTC_MASK = SMASK << UTC_SHIFT;
513     private static final int UAC_UNIT = 1 << UAC_SHIFT;
514     private static final int UTC_UNIT = 1 << UTC_SHIFT;
515    
516     // masks and units for dealing with e = (int)ctl
517     private static final int E_MASK = 0x7fffffff; // no STOP_BIT
518     private static final int EC_UNIT = 1 << EC_SHIFT;
519 dl 1.53
520     /**
521 dl 1.91 * The target parallelism level.
522 dl 1.61 */
523 dl 1.91 final int parallelism;
524 dl 1.61
525     /**
526 dl 1.91 * Index (mod submission queue length) of next element to take
527     * from submission queue.
528 dl 1.53 */
529 dl 1.91 volatile int queueBase;
530 dl 1.1
531     /**
532 dl 1.91 * Index (mod submission queue length) of next element to add
533     * in submission queue.
534 dl 1.53 */
535 dl 1.91 int queueTop;
536 dl 1.53
537 dl 1.1 /**
538 dl 1.91 * True when shutdown() has been called.
539 dl 1.1 */
540 dl 1.91 volatile boolean shutdown;
541 dl 1.1
542     /**
543 dl 1.53 * True if use local fifo, not default lifo, for local polling
544 dl 1.57 * Read by, and replicated by ForkJoinWorkerThreads
545 dl 1.1 */
546 dl 1.57 final boolean locallyFifo;
547 dl 1.1
548     /**
549 dl 1.91 * The number of threads in ForkJoinWorkerThreads.helpQuiescePool.
550     * When non-zero, suppresses automatic shutdown when active
551     * counts become zero.
552 dl 1.1 */
553 dl 1.91 volatile int quiescerCount;
554 dl 1.6
555     /**
556 dl 1.91 * The number of threads blocked in join.
557 dl 1.1 */
558 dl 1.91 volatile int blockedCount;
559 dl 1.1
560 dl 1.91 /**
561     * Counter for worker Thread names (unrelated to their poolIndex)
562     */
563     private volatile int nextWorkerNumber;
564 dl 1.1
565     /**
566 dl 1.91 * The index for the next created worker. Accessed under scanGuard.
567 dl 1.1 */
568 dl 1.91 private int nextWorkerIndex;
569 dl 1.58
570 dl 1.1 /**
571 dl 1.91 * SeqLock and index masking for for updates to workers array.
572     * Locked when SG_UNIT is set. Unlocking clears bit by adding
573     * SG_UNIT. Staleness of read-only operations can be checked by
574     * comparing scanGuard to value before the reads. The low 16 bits
575     * (i.e, anding with SMASK) hold (the smallest power of two
576     * covering all worker indices, minus one, and is used to avoid
577     * dealing with large numbers of null slots when the workers array
578     * is overallocated.
579 dl 1.85 */
580 dl 1.91 volatile int scanGuard;
581    
582     private static final int SG_UNIT = 1 << 16;
583 dl 1.85
584     /**
585 dl 1.91 * The wakeup interval (in nanoseconds) for a worker waiting for a
586     * task when the pool is quiescent to instead try to shrink the
587     * number of workers. The exact value does not matter too
588     * much. It must be short enough to release resources during
589     * sustained periods of idleness, but not so short that threads
590     * are continually re-created.
591 dl 1.56 */
592 dl 1.91 private static final long SHRINK_RATE =
593     4L * 1000L * 1000L * 1000L; // 4 seconds
594 dl 1.56
595     /**
596 dl 1.91 * Top-level loop for worker threads: On each step: if the
597     * previous step swept through all queues and found no tasks, or
598     * there are excess threads, then possibly blocks. Otherwise,
599     * scans for and, if found, executes a task. Returns when pool
600     * and/or worker terminate.
601 dl 1.61 *
602 dl 1.91 * @param w the worker
603 dl 1.58 */
604 dl 1.91 final void work(ForkJoinWorkerThread w) {
605     boolean swept = false; // true on empty scans
606     long c;
607     while (!w.terminate && (int)(c = ctl) >= 0) {
608     int a; // active count
609     if (!swept && (a = (int)(c >> AC_SHIFT)) <= 0)
610     swept = scan(w, a);
611     else if (tryAwaitWork(w, c))
612     swept = false;
613 dl 1.61 }
614     }
615    
616 dl 1.91 // Signalling
617    
618 dl 1.61 /**
619 dl 1.91 * Wakes up or creates a worker.
620 dl 1.53 */
621 dl 1.91 final void signalWork() {
622     /*
623     * The while condition is true if: (there is are too few total
624     * workers OR there is at least one waiter) AND (there are too
625     * few active workers OR the pool is terminating). The value
626     * of e distinguishes the remaining cases: zero (no waiters)
627     * for create, negative if terminating (in which case do
628     * nothing), else release a waiter. The secondary checks for
629     * release (non-null array etc) can fail if the pool begins
630     * terminating after the test, and don't impose any added cost
631     * because JVMs must perform null and bounds checks anyway.
632     */
633     long c; int e, u;
634     while ((((e = (int)(c = ctl)) | (u = (int)(c >>> 32))) &
635     (INT_SIGN|SHORT_SIGN)) == (INT_SIGN|SHORT_SIGN) && e >= 0) {
636     if (e > 0) { // release a waiting worker
637     int i; ForkJoinWorkerThread w; ForkJoinWorkerThread[] ws;
638     if ((ws = workers) == null ||
639     (i = ~e & SMASK) >= ws.length ||
640     (w = ws[i]) == null)
641     break;
642     long nc = (((long)(w.nextWait & E_MASK)) |
643     ((long)(u + UAC_UNIT) << 32));
644     if (w.eventCount == e &&
645     UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
646     w.eventCount = (e + EC_UNIT) & E_MASK;
647     if (w.parked)
648     UNSAFE.unpark(w);
649     break;
650     }
651     }
652     else if (UNSAFE.compareAndSwapLong
653     (this, ctlOffset, c,
654     (long)(((u + UTC_UNIT) & UTC_MASK) |
655     ((u + UAC_UNIT) & UAC_MASK)) << 32)) {
656     addWorker();
657     break;
658     }
659     }
660 dl 1.53 }
661    
662     /**
663 dl 1.91 * Variant of signalWork to help release waiters on rescans.
664     * Tries once to release a waiter if active count < 0.
665     *
666     * @return false if failed due to contention, else true
667 dl 1.53 */
668 dl 1.91 private boolean tryReleaseWaiter() {
669     long c; int e, i; ForkJoinWorkerThread w; ForkJoinWorkerThread[] ws;
670     if ((e = (int)(c = ctl)) > 0 &&
671     (int)(c >> AC_SHIFT) < 0 &&
672     (ws = workers) != null &&
673     (i = ~e & SMASK) < ws.length &&
674     (w = ws[i]) != null) {
675     long nc = ((long)(w.nextWait & E_MASK) |
676     ((c + AC_UNIT) & (AC_MASK|TC_MASK)));
677     if (w.eventCount != e ||
678     !UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc))
679 dl 1.53 return false;
680 dl 1.91 w.eventCount = (e + EC_UNIT) & E_MASK;
681     if (w.parked)
682     UNSAFE.unpark(w);
683 dl 1.53 }
684 dl 1.91 return true;
685 dl 1.53 }
686    
687 dl 1.91 // Scanning for tasks
688 dl 1.53
689     /**
690 dl 1.91 * Scans for and, if found, executes one task. Scans start at a
691     * random index of workers array, and randomly select the first
692     * (2*#workers)-1 probes, and then, if all empty, resort to 2
693     * circular sweeps, which is necessary to check quiescence. and
694     * taking a submission only if no stealable tasks were found. The
695     * steal code inside the loop is a specialized form of
696     * ForkJoinWorkerThread.deqTask, followed bookkeeping to support
697     * helpJoinTask and signal propagation. The code for submission
698     * queues is almost identical. On each steal, the worker completes
699     * not only the task, but also all local tasks that this task may
700     * have generated. On detecting staleness or contention when
701     * trying to take a task, this method returns without finishing
702     * sweep, which allows global state rechecks before retry.
703     *
704     * @param w the worker
705     * @param a the number of active workers
706     * @return true if swept all queues without finding a task
707 dl 1.53 */
708 dl 1.91 private boolean scan(ForkJoinWorkerThread w, int a) {
709     int g = scanGuard; // mask 0 avoids useless scans if only one active
710     int m = parallelism == 1 - a? 0 : g & SMASK;
711     ForkJoinWorkerThread[] ws = workers;
712     if (ws == null || ws.length <= m) // staleness check
713     return false;
714     for (int r = w.seed, k = r, j = -(m + m); j <= m + m; ++j) {
715     ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
716     ForkJoinWorkerThread v = ws[k & m];
717     if (v != null && (b = v.queueBase) != v.queueTop &&
718     (q = v.queue) != null && (i = (q.length - 1) & b) >= 0) {
719     long u = (i << ASHIFT) + ABASE;
720     if ((t = q[i]) != null && v.queueBase == b &&
721     UNSAFE.compareAndSwapObject(q, u, t, null)) {
722     int d = (v.queueBase = b + 1) - v.queueTop;
723     v.stealHint = w.poolIndex;
724     if (d != 0)
725     signalWork(); // propagate if nonempty
726     w.execTask(t);
727     }
728     r ^= r << 13; r ^= r >>> 17; w.seed = r ^ (r << 5);
729     return false; // store next seed
730     }
731     else if (j < 0) { // xorshift
732     r ^= r << 13; r ^= r >>> 17; k = r ^= r << 5;
733     }
734     else
735     ++k;
736     }
737     if (scanGuard != g) // staleness check
738     return false;
739     else { // try to take submission
740     ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
741     if ((b = queueBase) != queueTop &&
742     (q = submissionQueue) != null &&
743     (i = (q.length - 1) & b) >= 0) {
744     long u = (i << ASHIFT) + ABASE;
745     if ((t = q[i]) != null && queueBase == b &&
746     UNSAFE.compareAndSwapObject(q, u, t, null)) {
747     queueBase = b + 1;
748     w.execTask(t);
749     }
750     return false;
751     }
752     return true; // all queues empty
753 dl 1.53 }
754     }
755    
756     /**
757 dl 1.93 * Tries to enqueue worker w in wait queue and await change in
758     * worker's eventCount. If the pool is quiescent, possibly
759     * terminates worker upon exit. Otherwise, before blocking,
760     * rescans queues to avoid missed signals. Upon finding work,
761     * releases at least one worker (which may be the current
762     * worker). Rescans restart upon detected staleness or failure to
763     * release due to contention.
764 dl 1.91 *
765     * @param w the calling worker
766     * @param c the ctl value on entry
767     * @return true if waited or another thread was released upon enq
768 dl 1.53 */
769 dl 1.91 private boolean tryAwaitWork(ForkJoinWorkerThread w, long c) {
770     int v = w.eventCount;
771 dl 1.93 w.nextWait = (int)c; // w's successor record
772 dl 1.91 long nc = (long)(v & E_MASK) | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
773     if (ctl != c || !UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
774 dl 1.93 long d = ctl; // return true if lost to a deq, to force scan
775 dl 1.91 return (int)d != (int)c && ((d - c) & AC_MASK) >= 0L;
776     }
777 dl 1.93 for (int sc = w.stealCount; sc != 0;) { // accumulate stealCount
778     long s = stealCount;
779     if (UNSAFE.compareAndSwapLong(this, stealCountOffset, s, s + sc))
780     sc = w.stealCount = 0;
781     else if (w.eventCount != v)
782     return true; // update next time
783     }
784     if (parallelism + (int)(nc >> AC_SHIFT) == 0 &&
785 dl 1.92 blockedCount == 0 && quiescerCount == 0)
786 dl 1.93 idleAwaitWork(w, nc, c, v); // quiescent
787     for (boolean rescanned = false;;) {
788 dl 1.91 if (w.eventCount != v)
789     return true;
790 dl 1.93 if (!rescanned) {
791 dl 1.91 int g = scanGuard, m = g & SMASK;
792     ForkJoinWorkerThread[] ws = workers;
793     if (ws != null && m < ws.length) {
794     rescanned = true;
795     for (int i = 0; i <= m; ++i) {
796     ForkJoinWorkerThread u = ws[i];
797     if (u != null) {
798     if (u.queueBase != u.queueTop &&
799     !tryReleaseWaiter())
800     rescanned = false; // contended
801     if (w.eventCount != v)
802     return true;
803     }
804     }
805     }
806     if (scanGuard != g || // stale
807     (queueBase != queueTop && !tryReleaseWaiter()))
808     rescanned = false;
809     if (!rescanned)
810     Thread.yield(); // reduce contention
811     else
812     Thread.interrupted(); // clear before park
813     }
814     else {
815     w.parked = true; // must recheck
816     if (w.eventCount != v) {
817     w.parked = false;
818     return true;
819     }
820     LockSupport.park(this);
821     rescanned = w.parked = false;
822     }
823 dl 1.53 }
824     }
825    
826     /**
827 dl 1.93 * If inactivating worker w has caused pool to become
828     * quiescent, check for pool termination, and wait for event
829     * for up to SHRINK_RATE nanosecs (rescans are unnecessary in
830     * this case because quiescence reflects consensus about lack
831     * of work). On timeout, if ctl has not changed, terminate the
832     * worker. Upon its termination (see deregisterWorker), it may
833     * wake up another worker to possibly repeat this process.
834 dl 1.91 *
835     * @param w the calling worker
836 dl 1.93 * @param currentCtl the ctl value after enqueuing w
837     * @param prevCtl the ctl value if w terminated
838     * @param v the eventCount w awaits change
839     */
840     private void idleAwaitWork(ForkJoinWorkerThread w, long currentCtl,
841     long prevCtl, int v) {
842     if (w.eventCount == v) {
843     if (shutdown)
844     tryTerminate(false);
845     ForkJoinTask.helpExpungeStaleExceptions(); // help clean weak refs
846     while (ctl == currentCtl) {
847     long startTime = System.nanoTime();
848 dl 1.91 w.parked = true;
849 dl 1.93 if (w.eventCount == v) // must recheck
850 dl 1.91 LockSupport.parkNanos(this, SHRINK_RATE);
851     w.parked = false;
852 dl 1.93 if (w.eventCount != v)
853     break;
854     else if (System.nanoTime() - startTime < SHRINK_RATE)
855     Thread.interrupted(); // spurious wakeup
856     else if (UNSAFE.compareAndSwapLong(this, ctlOffset,
857     currentCtl, prevCtl)) {
858     w.terminate = true; // restore previous
859     w.eventCount = ((int)currentCtl + EC_UNIT) & E_MASK;
860     break;
861 dl 1.91 }
862     }
863     }
864 dl 1.53 }
865    
866 dl 1.91 // Submissions
867 dl 1.53
868     /**
869 dl 1.91 * Enqueues the given task in the submissionQueue. Same idea as
870     * ForkJoinWorkerThread.pushTask except for use of submissionLock.
871     *
872     * @param t the task
873 dl 1.53 */
874 dl 1.91 private void addSubmission(ForkJoinTask<?> t) {
875     final ReentrantLock lock = this.submissionLock;
876     lock.lock();
877     try {
878     ForkJoinTask<?>[] q; int s, m;
879     if ((q = submissionQueue) != null) { // ignore if queue removed
880     long u = (((s = queueTop) & (m = q.length-1)) << ASHIFT)+ABASE;
881     UNSAFE.putOrderedObject(q, u, t);
882     queueTop = s + 1;
883     if (s - queueBase == m)
884     growSubmissionQueue();
885 dl 1.66 }
886 dl 1.91 } finally {
887     lock.unlock();
888 dl 1.53 }
889 dl 1.91 signalWork();
890 dl 1.53 }
891    
892 dl 1.91 // (pollSubmission is defined below with exported methods)
893    
894 dl 1.53 /**
895 dl 1.91 * Creates or doubles submissionQueue array.
896     * Basically identical to ForkJoinWorkerThread version
897 dl 1.53 */
898 dl 1.91 private void growSubmissionQueue() {
899     ForkJoinTask<?>[] oldQ = submissionQueue;
900     int size = oldQ != null ? oldQ.length << 1 : INITIAL_QUEUE_CAPACITY;
901     if (size > MAXIMUM_QUEUE_CAPACITY)
902     throw new RejectedExecutionException("Queue capacity exceeded");
903     if (size < INITIAL_QUEUE_CAPACITY)
904     size = INITIAL_QUEUE_CAPACITY;
905     ForkJoinTask<?>[] q = submissionQueue = new ForkJoinTask<?>[size];
906     int mask = size - 1;
907     int top = queueTop;
908     int oldMask;
909     if (oldQ != null && (oldMask = oldQ.length - 1) >= 0) {
910     for (int b = queueBase; b != top; ++b) {
911     long u = ((b & oldMask) << ASHIFT) + ABASE;
912     Object x = UNSAFE.getObjectVolatile(oldQ, u);
913     if (x != null && UNSAFE.compareAndSwapObject(oldQ, u, x, null))
914     UNSAFE.putObjectVolatile
915     (q, ((b & mask) << ASHIFT) + ABASE, x);
916 dl 1.64 }
917     }
918     }
919    
920 dl 1.91 // Blocking support
921    
922 dl 1.64 /**
923 dl 1.91 * Tries to increment blockedCount, decrement active count
924     * (sometimes implicitly) and possibly release or create a
925     * compensating worker in preparation for blocking. Fails
926     * on contention or termination.
927     *
928     * @return true if the caller can block, else should recheck and retry
929     */
930     private boolean tryPreBlock() {
931     int b = blockedCount;
932     if (UNSAFE.compareAndSwapInt(this, blockedCountOffset, b, b + 1)) {
933     int pc = parallelism;
934     do {
935     ForkJoinWorkerThread[] ws; ForkJoinWorkerThread w;
936     int e, ac, tc, rc, i;
937     long c = ctl;
938     int u = (int)(c >>> 32);
939     if ((e = (int)c) < 0) {
940     // skip -- terminating
941     }
942     else if ((ac = (u >> UAC_SHIFT)) <= 0 && e != 0 &&
943     (ws = workers) != null &&
944     (i = ~e & SMASK) < ws.length &&
945     (w = ws[i]) != null) {
946     long nc = ((long)(w.nextWait & E_MASK) |
947     (c & (AC_MASK|TC_MASK)));
948     if (w.eventCount == e &&
949     UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
950     w.eventCount = (e + EC_UNIT) & E_MASK;
951     if (w.parked)
952     UNSAFE.unpark(w);
953     return true; // release an idle worker
954     }
955     }
956     else if ((tc = (short)(u >>> UTC_SHIFT)) >= 0 && ac + pc > 1) {
957     long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
958     if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc))
959     return true; // no compensation needed
960     }
961     else if (tc + pc < MAX_ID) {
962     long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
963     if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
964     addWorker();
965     return true; // create a replacement
966     }
967 dl 1.61 }
968 dl 1.91 // try to back out on any failure and let caller retry
969     } while (!UNSAFE.compareAndSwapInt(this, blockedCountOffset,
970     b = blockedCount, b - 1));
971 dl 1.53 }
972 dl 1.91 return false;
973 dl 1.64 }
974    
975 dl 1.91 /**
976     * Decrements blockedCount and increments active count
977     */
978     private void postBlock() {
979     long c;
980     do {} while (!UNSAFE.compareAndSwapLong(this, ctlOffset, // no mask
981     c = ctl, c + AC_UNIT));
982     int b;
983     do {} while(!UNSAFE.compareAndSwapInt(this, blockedCountOffset,
984     b = blockedCount, b - 1));
985     }
986 dl 1.61
987     /**
988 dl 1.91 * Possibly blocks waiting for the given task to complete, or
989     * cancels the task if terminating. Fails to wait if contended.
990     *
991     * @param joinMe the task
992 dl 1.61 */
993 dl 1.91 final void tryAwaitJoin(ForkJoinTask<?> joinMe) {
994     int s;
995     Thread.interrupted(); // clear interrupts before checking termination
996     if (joinMe.status >= 0) {
997     if (tryPreBlock()) {
998     joinMe.tryAwaitDone(0L);
999     postBlock();
1000     }
1001     if ((ctl & STOP_BIT) != 0L)
1002     joinMe.cancelIgnoringExceptions();
1003     }
1004 dl 1.61 }
1005    
1006     /**
1007 dl 1.91 * Possibly blocks the given worker waiting for joinMe to
1008     * complete or timeout
1009     *
1010     * @param joinMe the task
1011     * @param millis the wait time for underlying Object.wait
1012 dl 1.61 */
1013 dl 1.91 final void timedAwaitJoin(ForkJoinTask<?> joinMe, long nanos) {
1014     while (joinMe.status >= 0) {
1015     Thread.interrupted();
1016     if ((ctl & STOP_BIT) != 0L) {
1017     joinMe.cancelIgnoringExceptions();
1018     break;
1019     }
1020     if (tryPreBlock()) {
1021     long last = System.nanoTime();
1022     while (joinMe.status >= 0) {
1023     long millis = TimeUnit.NANOSECONDS.toMillis(nanos);
1024     if (millis <= 0)
1025     break;
1026     joinMe.tryAwaitDone(millis);
1027     if (joinMe.status < 0)
1028     break;
1029     if ((ctl & STOP_BIT) != 0L) {
1030     joinMe.cancelIgnoringExceptions();
1031     break;
1032     }
1033     long now = System.nanoTime();
1034     nanos -= now - last;
1035     last = now;
1036     }
1037     postBlock();
1038     break;
1039     }
1040 dl 1.64 }
1041     }
1042    
1043     /**
1044 dl 1.91 * If necessary, compensates for blocker, and blocks
1045 dl 1.64 */
1046 dl 1.91 private void awaitBlocker(ManagedBlocker blocker)
1047     throws InterruptedException {
1048     while (!blocker.isReleasable()) {
1049     if (tryPreBlock()) {
1050 dl 1.66 try {
1051 dl 1.91 do {} while (!blocker.isReleasable() && !blocker.block());
1052     } finally {
1053     postBlock();
1054 dl 1.66 }
1055 dl 1.91 break;
1056 dl 1.64 }
1057     }
1058     }
1059    
1060 dl 1.91 // Creating, registering and deregistring workers
1061    
1062 dl 1.64 /**
1063 dl 1.91 * Tries to create and start a worker; minimally rolls back counts
1064     * on failure.
1065 dl 1.64 */
1066 dl 1.91 private void addWorker() {
1067     Throwable ex = null;
1068     ForkJoinWorkerThread t = null;
1069     try {
1070     t = factory.newThread(this);
1071     } catch (Throwable e) {
1072     ex = e;
1073     }
1074     if (t == null) { // null or exceptional factory return
1075     long c; // adjust counts
1076     do {} while (!UNSAFE.compareAndSwapLong
1077     (this, ctlOffset, c = ctl,
1078     (((c - AC_UNIT) & AC_MASK) |
1079     ((c - TC_UNIT) & TC_MASK) |
1080     (c & ~(AC_MASK|TC_MASK)))));
1081     // Propagate exception if originating from an external caller
1082     if (!tryTerminate(false) && ex != null &&
1083     !(Thread.currentThread() instanceof ForkJoinWorkerThread))
1084     UNSAFE.throwException(ex);
1085     }
1086     else
1087     t.start();
1088 dl 1.61 }
1089    
1090 dl 1.53 /**
1091 dl 1.91 * Callback from ForkJoinWorkerThread constructor to assign a
1092     * public name
1093 dl 1.53 */
1094 dl 1.91 final String nextWorkerName() {
1095     for (int n;;) {
1096     if (UNSAFE.compareAndSwapInt(this, nextWorkerNumberOffset,
1097     n = nextWorkerNumber, ++n))
1098     return workerNamePrefix + n;
1099 dl 1.53 }
1100     }
1101    
1102     /**
1103 dl 1.91 * Callback from ForkJoinWorkerThread constructor to
1104     * determine its poolIndex and record in workers array.
1105 dl 1.56 *
1106 dl 1.91 * @param w the worker
1107     * @return the worker's pool index
1108 dl 1.53 */
1109 dl 1.91 final int registerWorker(ForkJoinWorkerThread w) {
1110     /*
1111     * In the typical case, a new worker acquires the lock, uses
1112     * next available index and returns quickly. Since we should
1113     * not block callers (ultimately from signalWork or
1114     * tryPreBlock) waiting for the lock needed to do this, we
1115     * instead help release other workers while waiting for the
1116     * lock.
1117     */
1118     for (int g;;) {
1119     ForkJoinWorkerThread[] ws;
1120     if (((g = scanGuard) & SG_UNIT) == 0 &&
1121     UNSAFE.compareAndSwapInt(this, scanGuardOffset,
1122     g, g | SG_UNIT)) {
1123     int k = nextWorkerIndex;
1124     try {
1125     if ((ws = workers) != null) { // ignore on shutdown
1126     int n = ws.length;
1127     if (k < 0 || k >= n || ws[k] != null) {
1128     for (k = 0; k < n && ws[k] != null; ++k)
1129     ;
1130     if (k == n)
1131     ws = workers = Arrays.copyOf(ws, n << 1);
1132     }
1133     ws[k] = w;
1134     nextWorkerIndex = k + 1;
1135     int m = g & SMASK;
1136     g = k >= m? ((m << 1) + 1) & SMASK : g + (SG_UNIT<<1);
1137     }
1138     } finally {
1139     scanGuard = g;
1140     }
1141     return k;
1142 dl 1.82 }
1143 dl 1.91 else if ((ws = workers) != null) { // help release others
1144     for (ForkJoinWorkerThread u : ws) {
1145     if (u != null && u.queueBase != u.queueTop) {
1146     if (tryReleaseWaiter())
1147 dl 1.85 break;
1148 dl 1.83 }
1149     }
1150 dl 1.53 }
1151     }
1152     }
1153    
1154     /**
1155 dl 1.91 * Final callback from terminating worker. Removes record of
1156     * worker from array, and adjusts counts. If pool is shutting
1157     * down, tries to complete termination.
1158     *
1159     * @param w the worker
1160 dl 1.53 */
1161 dl 1.91 final void deregisterWorker(ForkJoinWorkerThread w, Throwable ex) {
1162     int idx = w.poolIndex;
1163     int sc = w.stealCount;
1164     int steps = 0;
1165     // Remove from array, adjust worker counts and collect steal count.
1166     // We can intermix failed removes or adjusts with steal updates
1167     do {
1168     long s, c;
1169     int g;
1170     if (steps == 0 && ((g = scanGuard) & SG_UNIT) == 0 &&
1171     UNSAFE.compareAndSwapInt(this, scanGuardOffset,
1172     g, g |= SG_UNIT)) {
1173     ForkJoinWorkerThread[] ws = workers;
1174     if (ws != null && idx >= 0 &&
1175     idx < ws.length && ws[idx] == w)
1176     ws[idx] = null; // verify
1177     nextWorkerIndex = idx;
1178     scanGuard = g + SG_UNIT;
1179     steps = 1;
1180 dl 1.60 }
1181 dl 1.91 if (steps == 1 &&
1182     UNSAFE.compareAndSwapLong(this, ctlOffset, c = ctl,
1183     (((c - AC_UNIT) & AC_MASK) |
1184     ((c - TC_UNIT) & TC_MASK) |
1185     (c & ~(AC_MASK|TC_MASK)))))
1186     steps = 2;
1187     if (sc != 0 &&
1188     UNSAFE.compareAndSwapLong(this, stealCountOffset,
1189     s = stealCount, s + sc))
1190     sc = 0;
1191     } while (steps != 2 || sc != 0);
1192     if (!tryTerminate(false)) {
1193     if (ex != null) // possibly replace if died abnormally
1194     signalWork();
1195     else
1196     tryReleaseWaiter();
1197 dl 1.53 }
1198 dl 1.59 }
1199 dl 1.54
1200 dl 1.91 // Shutdown and termination
1201    
1202 dl 1.54 /**
1203 dl 1.53 * Possibly initiates and/or completes termination.
1204     *
1205     * @param now if true, unconditionally terminate, else only
1206     * if shutdown and empty queue and no active workers
1207     * @return true if now terminating or terminated
1208 dl 1.1 */
1209 dl 1.53 private boolean tryTerminate(boolean now) {
1210 dl 1.91 long c;
1211     while (((c = ctl) & STOP_BIT) == 0) {
1212     if (!now) {
1213     if ((int)(c >> AC_SHIFT) != -parallelism)
1214     return false;
1215     if (!shutdown || blockedCount != 0 || quiescerCount != 0 ||
1216     queueTop - queueBase > 0) {
1217     if (ctl == c) // staleness check
1218     return false;
1219     continue;
1220     }
1221     }
1222     if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, c | STOP_BIT))
1223     startTerminating();
1224     }
1225     if ((short)(c >>> TC_SHIFT) == -parallelism) {
1226     submissionLock.lock();
1227     termination.signalAll();
1228     submissionLock.unlock();
1229 dl 1.53 }
1230 dl 1.4 return true;
1231 dl 1.1 }
1232    
1233     /**
1234 dl 1.91 * Runs up to three passes through workers: (0) Setting
1235     * termination status for each worker, followed by wakeups up
1236     * queued workers (1) helping cancel tasks (2) interrupting
1237     * lagging threads (likely in external tasks, but possibly also
1238     * blocked in joins). Each pass repeats previous steps because of
1239     * potential lagging thread creation.
1240 dl 1.53 */
1241     private void startTerminating() {
1242 dl 1.61 cancelSubmissions();
1243 dl 1.91 for (int pass = 0; pass < 3; ++pass) {
1244     ForkJoinWorkerThread[] ws = workers;
1245     if (ws != null) {
1246     for (ForkJoinWorkerThread w : ws) {
1247     if (w != null) {
1248     w.terminate = true;
1249     if (pass > 0) {
1250     w.cancelTasks();
1251     if (pass > 1 && !w.isInterrupted()) {
1252     try {
1253     w.interrupt();
1254     } catch (SecurityException ignore) {
1255     }
1256 dl 1.61 }
1257     }
1258     }
1259     }
1260 dl 1.91 terminateWaiters();
1261 dl 1.61 }
1262 dl 1.56 }
1263     }
1264    
1265     /**
1266 dl 1.91 * Polls and cancels all submissions. Called only during termination.
1267 dl 1.56 */
1268     private void cancelSubmissions() {
1269 dl 1.91 while (queueBase != queueTop) {
1270     ForkJoinTask<?> task = pollSubmission();
1271     if (task != null) {
1272     try {
1273     task.cancel(false);
1274     } catch (Throwable ignore) {
1275     }
1276     }
1277     }
1278     }
1279    
1280     /**
1281     * Tries to set the termination status of waiting workers, and
1282     * then wake them up (after which they will terminate).
1283     */
1284     private void terminateWaiters() {
1285     ForkJoinWorkerThread[] ws = workers;
1286     if (ws != null) {
1287     ForkJoinWorkerThread w; long c; int i, e;
1288     int n = ws.length;
1289     while ((i = ~(e = (int)(c = ctl)) & SMASK) < n &&
1290     (w = ws[i]) != null && w.eventCount == (e & E_MASK)) {
1291     if (UNSAFE.compareAndSwapLong(this, ctlOffset, c,
1292     (long)(w.nextWait & E_MASK) |
1293     ((c + AC_UNIT) & AC_MASK) |
1294     (c & (TC_MASK|STOP_BIT)))) {
1295     w.terminate = true;
1296     w.eventCount = e + EC_UNIT;
1297     if (w.parked)
1298     UNSAFE.unpark(w);
1299     }
1300 dl 1.53 }
1301     }
1302 dl 1.56 }
1303    
1304 dl 1.91 // misc ForkJoinWorkerThread support
1305 dl 1.53
1306     /**
1307 dl 1.91 * Increment or decrement quiescerCount. Needed only to prevent
1308     * triggering shutdown if a worker is transiently inactive while
1309     * checking quiescence.
1310     *
1311     * @param delta 1 for increment, -1 for decrement
1312 dl 1.1 */
1313 dl 1.91 final void addQuiescerCount(int delta) {
1314     int c;
1315     do {} while(!UNSAFE.compareAndSwapInt(this, quiescerCountOffset,
1316     c = quiescerCount, c + delta));
1317 dl 1.1 }
1318    
1319     /**
1320 dl 1.91 * Directly increment or decrement active count without
1321     * queuing. This method is used to transiently assert inactivation
1322     * while checking quiescence.
1323 dl 1.61 *
1324 dl 1.91 * @param delta 1 for increment, -1 for decrement
1325 dl 1.1 */
1326 dl 1.91 final void addActiveCount(int delta) {
1327     long d = delta < 0 ? -AC_UNIT : AC_UNIT;
1328     long c;
1329     do {} while (!UNSAFE.compareAndSwapLong(this, ctlOffset, c = ctl,
1330     ((c + d) & AC_MASK) |
1331     (c & ~AC_MASK)));
1332 dl 1.1 }
1333    
1334     /**
1335 dl 1.53 * Returns the approximate (non-atomic) number of idle threads per
1336     * active thread.
1337     */
1338     final int idlePerActive() {
1339 dl 1.91 // Approximate at powers of two for small values, saturate past 4
1340     int p = parallelism;
1341     int a = p + (int)(ctl >> AC_SHIFT);
1342     return (a > (p >>>= 1) ? 0 :
1343     a > (p >>>= 1) ? 1 :
1344     a > (p >>>= 1) ? 2 :
1345     a > (p >>>= 1) ? 4 :
1346     8);
1347 dl 1.53 }
1348    
1349 dl 1.91 // Exported methods
1350 dl 1.1
1351     // Constructors
1352    
1353     /**
1354 dl 1.42 * Creates a {@code ForkJoinPool} with parallelism equal to {@link
1355 dl 1.57 * java.lang.Runtime#availableProcessors}, using the {@linkplain
1356     * #defaultForkJoinWorkerThreadFactory default thread factory},
1357     * no UncaughtExceptionHandler, and non-async LIFO processing mode.
1358 jsr166 1.17 *
1359 dl 1.1 * @throws SecurityException if a security manager exists and
1360     * the caller is not permitted to modify threads
1361     * because it does not hold {@link
1362 jsr166 1.17 * java.lang.RuntimePermission}{@code ("modifyThread")}
1363 dl 1.1 */
1364     public ForkJoinPool() {
1365     this(Runtime.getRuntime().availableProcessors(),
1366 dl 1.57 defaultForkJoinWorkerThreadFactory, null, false);
1367 dl 1.1 }
1368    
1369     /**
1370 dl 1.42 * Creates a {@code ForkJoinPool} with the indicated parallelism
1371 dl 1.57 * level, the {@linkplain
1372     * #defaultForkJoinWorkerThreadFactory default thread factory},
1373     * no UncaughtExceptionHandler, and non-async LIFO processing mode.
1374 jsr166 1.17 *
1375 dl 1.42 * @param parallelism the parallelism level
1376 dl 1.1 * @throws IllegalArgumentException if parallelism less than or
1377 jsr166 1.47 * equal to zero, or greater than implementation limit
1378 dl 1.1 * @throws SecurityException if a security manager exists and
1379     * the caller is not permitted to modify threads
1380     * because it does not hold {@link
1381 jsr166 1.17 * java.lang.RuntimePermission}{@code ("modifyThread")}
1382 dl 1.1 */
1383     public ForkJoinPool(int parallelism) {
1384 dl 1.57 this(parallelism, defaultForkJoinWorkerThreadFactory, null, false);
1385 dl 1.1 }
1386    
1387     /**
1388 dl 1.57 * Creates a {@code ForkJoinPool} with the given parameters.
1389 jsr166 1.17 *
1390 dl 1.57 * @param parallelism the parallelism level. For default value,
1391     * use {@link java.lang.Runtime#availableProcessors}.
1392     * @param factory the factory for creating new threads. For default value,
1393     * use {@link #defaultForkJoinWorkerThreadFactory}.
1394 dl 1.59 * @param handler the handler for internal worker threads that
1395     * terminate due to unrecoverable errors encountered while executing
1396 jsr166 1.73 * tasks. For default value, use {@code null}.
1397 dl 1.59 * @param asyncMode if true,
1398 dl 1.57 * establishes local first-in-first-out scheduling mode for forked
1399     * tasks that are never joined. This mode may be more appropriate
1400     * than default locally stack-based mode in applications in which
1401     * worker threads only process event-style asynchronous tasks.
1402 jsr166 1.73 * For default value, use {@code false}.
1403 dl 1.1 * @throws IllegalArgumentException if parallelism less than or
1404 jsr166 1.47 * equal to zero, or greater than implementation limit
1405 jsr166 1.48 * @throws NullPointerException if the factory is null
1406 dl 1.1 * @throws SecurityException if a security manager exists and
1407     * the caller is not permitted to modify threads
1408     * because it does not hold {@link
1409 jsr166 1.17 * java.lang.RuntimePermission}{@code ("modifyThread")}
1410 dl 1.1 */
1411 dl 1.59 public ForkJoinPool(int parallelism,
1412 dl 1.57 ForkJoinWorkerThreadFactory factory,
1413     Thread.UncaughtExceptionHandler handler,
1414     boolean asyncMode) {
1415 dl 1.53 checkPermission();
1416     if (factory == null)
1417     throw new NullPointerException();
1418 dl 1.91 if (parallelism <= 0 || parallelism > MAX_ID)
1419 dl 1.1 throw new IllegalArgumentException();
1420 dl 1.53 this.parallelism = parallelism;
1421 dl 1.1 this.factory = factory;
1422 dl 1.57 this.ueh = handler;
1423     this.locallyFifo = asyncMode;
1424 dl 1.91 long np = (long)(-parallelism); // offset ctl counts
1425     this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
1426     this.submissionQueue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
1427     // initialize workers array with room for 2*parallelism if possible
1428     int n = parallelism << 1;
1429     if (n >= MAX_ID)
1430     n = MAX_ID;
1431     else { // See Hackers Delight, sec 3.2, where n < (1 << 16)
1432     n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8;
1433     }
1434     workers = new ForkJoinWorkerThread[n + 1];
1435     this.submissionLock = new ReentrantLock();
1436     this.termination = submissionLock.newCondition();
1437     StringBuilder sb = new StringBuilder("ForkJoinPool-");
1438     sb.append(poolNumberGenerator.incrementAndGet());
1439     sb.append("-worker-");
1440     this.workerNamePrefix = sb.toString();
1441 dl 1.1 }
1442    
1443     // Execution methods
1444    
1445     /**
1446 jsr166 1.17 * Performs the given task, returning its result upon completion.
1447 dl 1.91 * If the computation encounters an unchecked Exception or Error,
1448     * it is rethrown as the outcome of this invocation. Rethrown
1449     * exceptions behave in the same way as regular exceptions, but,
1450     * when possible, contain stack traces (as displayed for example
1451     * using {@code ex.printStackTrace()}) of both the current thread
1452     * as well as the thread actually encountering the exception;
1453     * minimally only the latter.
1454 jsr166 1.17 *
1455 dl 1.1 * @param task the task
1456     * @return the task's result
1457 jsr166 1.48 * @throws NullPointerException if the task is null
1458     * @throws RejectedExecutionException if the task cannot be
1459     * scheduled for execution
1460 dl 1.1 */
1461     public <T> T invoke(ForkJoinTask<T> task) {
1462 dl 1.91 Thread t = Thread.currentThread();
1463 dl 1.82 if (task == null)
1464     throw new NullPointerException();
1465 dl 1.91 if (shutdown)
1466 dl 1.82 throw new RejectedExecutionException();
1467     if ((t instanceof ForkJoinWorkerThread) &&
1468     ((ForkJoinWorkerThread)t).pool == this)
1469     return task.invoke(); // bypass submit if in same pool
1470     else {
1471 dl 1.91 addSubmission(task);
1472 dl 1.82 return task.join();
1473     }
1474     }
1475    
1476     /**
1477     * Unless terminating, forks task if within an ongoing FJ
1478     * computation in the current pool, else submits as external task.
1479     */
1480     private <T> void forkOrSubmit(ForkJoinTask<T> task) {
1481 dl 1.91 ForkJoinWorkerThread w;
1482     Thread t = Thread.currentThread();
1483     if (shutdown)
1484 dl 1.82 throw new RejectedExecutionException();
1485     if ((t instanceof ForkJoinWorkerThread) &&
1486 dl 1.91 (w = (ForkJoinWorkerThread)t).pool == this)
1487     w.pushTask(task);
1488 dl 1.82 else
1489 dl 1.91 addSubmission(task);
1490 dl 1.1 }
1491    
1492     /**
1493     * Arranges for (asynchronous) execution of the given task.
1494 jsr166 1.17 *
1495 dl 1.1 * @param task the task
1496 jsr166 1.48 * @throws NullPointerException if the task is null
1497     * @throws RejectedExecutionException if the task cannot be
1498     * scheduled for execution
1499 dl 1.1 */
1500 dl 1.37 public void execute(ForkJoinTask<?> task) {
1501 dl 1.82 if (task == null)
1502     throw new NullPointerException();
1503     forkOrSubmit(task);
1504 dl 1.1 }
1505    
1506     // AbstractExecutorService methods
1507    
1508 jsr166 1.48 /**
1509     * @throws NullPointerException if the task is null
1510     * @throws RejectedExecutionException if the task cannot be
1511     * scheduled for execution
1512     */
1513 dl 1.1 public void execute(Runnable task) {
1514 dl 1.82 if (task == null)
1515     throw new NullPointerException();
1516 dl 1.23 ForkJoinTask<?> job;
1517 jsr166 1.26 if (task instanceof ForkJoinTask<?>) // avoid re-wrap
1518     job = (ForkJoinTask<?>) task;
1519 dl 1.23 else
1520 dl 1.33 job = ForkJoinTask.adapt(task, null);
1521 dl 1.82 forkOrSubmit(job);
1522 dl 1.1 }
1523    
1524 jsr166 1.48 /**
1525 dl 1.57 * Submits a ForkJoinTask for execution.
1526     *
1527     * @param task the task to submit
1528     * @return the task
1529     * @throws NullPointerException if the task is null
1530     * @throws RejectedExecutionException if the task cannot be
1531     * scheduled for execution
1532     */
1533     public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
1534 dl 1.82 if (task == null)
1535     throw new NullPointerException();
1536     forkOrSubmit(task);
1537 dl 1.57 return task;
1538     }
1539    
1540     /**
1541 jsr166 1.48 * @throws NullPointerException if the task is null
1542     * @throws RejectedExecutionException if the task cannot be
1543     * scheduled for execution
1544     */
1545 dl 1.1 public <T> ForkJoinTask<T> submit(Callable<T> task) {
1546 dl 1.82 if (task == null)
1547     throw new NullPointerException();
1548 dl 1.33 ForkJoinTask<T> job = ForkJoinTask.adapt(task);
1549 dl 1.82 forkOrSubmit(job);
1550 dl 1.1 return job;
1551     }
1552    
1553 jsr166 1.48 /**
1554     * @throws NullPointerException if the task is null
1555     * @throws RejectedExecutionException if the task cannot be
1556     * scheduled for execution
1557     */
1558 dl 1.1 public <T> ForkJoinTask<T> submit(Runnable task, T result) {
1559 dl 1.82 if (task == null)
1560     throw new NullPointerException();
1561 dl 1.33 ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
1562 dl 1.82 forkOrSubmit(job);
1563 dl 1.1 return job;
1564     }
1565    
1566 jsr166 1.48 /**
1567     * @throws NullPointerException if the task is null
1568     * @throws RejectedExecutionException if the task cannot be
1569     * scheduled for execution
1570     */
1571 dl 1.1 public ForkJoinTask<?> submit(Runnable task) {
1572 dl 1.82 if (task == null)
1573     throw new NullPointerException();
1574 dl 1.23 ForkJoinTask<?> job;
1575 jsr166 1.26 if (task instanceof ForkJoinTask<?>) // avoid re-wrap
1576     job = (ForkJoinTask<?>) task;
1577 dl 1.23 else
1578 dl 1.33 job = ForkJoinTask.adapt(task, null);
1579 dl 1.82 forkOrSubmit(job);
1580 dl 1.1 return job;
1581     }
1582    
1583     /**
1584 jsr166 1.48 * @throws NullPointerException {@inheritDoc}
1585     * @throws RejectedExecutionException {@inheritDoc}
1586     */
1587 dl 1.1 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
1588 jsr166 1.20 ArrayList<ForkJoinTask<T>> forkJoinTasks =
1589 dl 1.1 new ArrayList<ForkJoinTask<T>>(tasks.size());
1590 jsr166 1.20 for (Callable<T> task : tasks)
1591 dl 1.33 forkJoinTasks.add(ForkJoinTask.adapt(task));
1592 jsr166 1.20 invoke(new InvokeAll<T>(forkJoinTasks));
1593    
1594     @SuppressWarnings({"unchecked", "rawtypes"})
1595 dl 1.54 List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
1596 jsr166 1.20 return futures;
1597 dl 1.1 }
1598    
1599     static final class InvokeAll<T> extends RecursiveAction {
1600     final ArrayList<ForkJoinTask<T>> tasks;
1601     InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
1602     public void compute() {
1603 jsr166 1.17 try { invokeAll(tasks); }
1604     catch (Exception ignore) {}
1605 dl 1.1 }
1606 jsr166 1.18 private static final long serialVersionUID = -7914297376763021607L;
1607 dl 1.1 }
1608    
1609     /**
1610 jsr166 1.17 * Returns the factory used for constructing new workers.
1611 dl 1.1 *
1612     * @return the factory used for constructing new workers
1613     */
1614     public ForkJoinWorkerThreadFactory getFactory() {
1615     return factory;
1616     }
1617    
1618     /**
1619 dl 1.2 * Returns the handler for internal worker threads that terminate
1620     * due to unrecoverable errors encountered while executing tasks.
1621 jsr166 1.17 *
1622 jsr166 1.28 * @return the handler, or {@code null} if none
1623 dl 1.2 */
1624     public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
1625 dl 1.53 return ueh;
1626 dl 1.2 }
1627    
1628     /**
1629 dl 1.42 * Returns the targeted parallelism level of this pool.
1630 dl 1.1 *
1631 dl 1.42 * @return the targeted parallelism level of this pool
1632 dl 1.1 */
1633     public int getParallelism() {
1634     return parallelism;
1635     }
1636    
1637     /**
1638     * Returns the number of worker threads that have started but not
1639 jsr166 1.76 * yet terminated. The result returned by this method may differ
1640 jsr166 1.29 * from {@link #getParallelism} when threads are created to
1641 dl 1.1 * maintain parallelism when others are cooperatively blocked.
1642     *
1643     * @return the number of worker threads
1644     */
1645     public int getPoolSize() {
1646 dl 1.91 return parallelism + (short)(ctl >>> TC_SHIFT);
1647 dl 1.1 }
1648    
1649     /**
1650 jsr166 1.28 * Returns {@code true} if this pool uses local first-in-first-out
1651 jsr166 1.16 * scheduling mode for forked tasks that are never joined.
1652 dl 1.6 *
1653 jsr166 1.28 * @return {@code true} if this pool uses async mode
1654 dl 1.6 */
1655     public boolean getAsyncMode() {
1656     return locallyFifo;
1657     }
1658    
1659     /**
1660 dl 1.2 * Returns an estimate of the number of worker threads that are
1661     * not blocked waiting to join tasks or for other managed
1662 dl 1.53 * synchronization. This method may overestimate the
1663     * number of running threads.
1664 dl 1.1 *
1665     * @return the number of worker threads
1666     */
1667     public int getRunningThreadCount() {
1668 dl 1.91 int r = parallelism + (int)(ctl >> AC_SHIFT);
1669     return r <= 0? 0 : r; // suppress momentarily negative values
1670 dl 1.1 }
1671    
1672     /**
1673 dl 1.2 * Returns an estimate of the number of threads that are currently
1674 dl 1.1 * stealing or executing tasks. This method may overestimate the
1675     * number of active threads.
1676 jsr166 1.17 *
1677 jsr166 1.16 * @return the number of active threads
1678 dl 1.1 */
1679     public int getActiveThreadCount() {
1680 dl 1.91 int r = parallelism + (int)(ctl >> AC_SHIFT) + blockedCount;
1681     return r <= 0? 0 : r; // suppress momentarily negative values
1682 dl 1.1 }
1683    
1684     /**
1685 jsr166 1.28 * Returns {@code true} if all worker threads are currently idle.
1686     * An idle worker is one that cannot obtain a task to execute
1687     * because none are available to steal from other threads, and
1688     * there are no pending submissions to the pool. This method is
1689     * conservative; it might not return {@code true} immediately upon
1690     * idleness of all threads, but will eventually become true if
1691     * threads remain inactive.
1692 jsr166 1.17 *
1693 jsr166 1.28 * @return {@code true} if all threads are currently idle
1694 dl 1.1 */
1695     public boolean isQuiescent() {
1696 dl 1.91 return parallelism + (int)(ctl >> AC_SHIFT) + blockedCount == 0;
1697 dl 1.1 }
1698    
1699     /**
1700     * Returns an estimate of the total number of tasks stolen from
1701     * one thread's work queue by another. The reported value
1702     * underestimates the actual total number of steals when the pool
1703     * is not quiescent. This value may be useful for monitoring and
1704 jsr166 1.17 * tuning fork/join programs: in general, steal counts should be
1705 dl 1.1 * high enough to keep threads busy, but low enough to avoid
1706     * overhead and contention across threads.
1707 jsr166 1.17 *
1708 jsr166 1.16 * @return the number of steals
1709 dl 1.1 */
1710     public long getStealCount() {
1711 dl 1.53 return stealCount;
1712 dl 1.1 }
1713    
1714     /**
1715 dl 1.2 * Returns an estimate of the total number of tasks currently held
1716     * in queues by worker threads (but not including tasks submitted
1717     * to the pool that have not begun executing). This value is only
1718     * an approximation, obtained by iterating across all threads in
1719     * the pool. This method may be useful for tuning task
1720     * granularities.
1721 jsr166 1.17 *
1722 jsr166 1.16 * @return the number of queued tasks
1723 dl 1.1 */
1724     public long getQueuedTaskCount() {
1725     long count = 0;
1726 dl 1.91 ForkJoinWorkerThread[] ws;
1727     if ((short)(ctl >>> TC_SHIFT) > -parallelism &&
1728     (ws = workers) != null) {
1729     for (ForkJoinWorkerThread w : ws)
1730     if (w != null)
1731     count -= w.queueBase - w.queueTop; // must read base first
1732     }
1733 dl 1.1 return count;
1734     }
1735    
1736     /**
1737 jsr166 1.40 * Returns an estimate of the number of tasks submitted to this
1738 dl 1.91 * pool that have not yet begun executing. This meThod may take
1739     * time proportional to the number of submissions.
1740 jsr166 1.17 *
1741 jsr166 1.16 * @return the number of queued submissions
1742 dl 1.1 */
1743     public int getQueuedSubmissionCount() {
1744 dl 1.91 return -queueBase + queueTop;
1745 dl 1.1 }
1746    
1747     /**
1748 jsr166 1.28 * Returns {@code true} if there are any tasks submitted to this
1749     * pool that have not yet begun executing.
1750 jsr166 1.17 *
1751 jsr166 1.16 * @return {@code true} if there are any queued submissions
1752 dl 1.1 */
1753     public boolean hasQueuedSubmissions() {
1754 dl 1.91 return queueBase != queueTop;
1755 dl 1.1 }
1756    
1757     /**
1758     * Removes and returns the next unexecuted submission if one is
1759     * available. This method may be useful in extensions to this
1760     * class that re-assign work in systems with multiple pools.
1761 jsr166 1.17 *
1762 jsr166 1.28 * @return the next submission, or {@code null} if none
1763 dl 1.1 */
1764     protected ForkJoinTask<?> pollSubmission() {
1765 dl 1.91 ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
1766     while ((b = queueBase) != queueTop &&
1767     (q = submissionQueue) != null &&
1768     (i = (q.length - 1) & b) >= 0) {
1769     long u = (i << ASHIFT) + ABASE;
1770     if ((t = q[i]) != null &&
1771     queueBase == b &&
1772     UNSAFE.compareAndSwapObject(q, u, t, null)) {
1773     queueBase = b + 1;
1774     return t;
1775     }
1776     }
1777     return null;
1778 dl 1.1 }
1779    
1780     /**
1781 dl 1.6 * Removes all available unexecuted submitted and forked tasks
1782     * from scheduling queues and adds them to the given collection,
1783     * without altering their execution status. These may include
1784 jsr166 1.41 * artificially generated or wrapped tasks. This method is
1785     * designed to be invoked only when the pool is known to be
1786 dl 1.6 * quiescent. Invocations at other times may not remove all
1787     * tasks. A failure encountered while attempting to add elements
1788 jsr166 1.16 * to collection {@code c} may result in elements being in
1789 dl 1.6 * neither, either or both collections when the associated
1790     * exception is thrown. The behavior of this operation is
1791     * undefined if the specified collection is modified while the
1792     * operation is in progress.
1793 jsr166 1.17 *
1794 dl 1.6 * @param c the collection to transfer elements into
1795     * @return the number of elements transferred
1796     */
1797 dl 1.30 protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
1798 dl 1.91 int count = 0;
1799     while (queueBase != queueTop) {
1800     ForkJoinTask<?> t = pollSubmission();
1801     if (t != null) {
1802     c.add(t);
1803     ++count;
1804     }
1805     }
1806     ForkJoinWorkerThread[] ws;
1807     if ((short)(ctl >>> TC_SHIFT) > -parallelism &&
1808     (ws = workers) != null) {
1809     for (ForkJoinWorkerThread w : ws)
1810     if (w != null)
1811     count += w.drainTasksTo(c);
1812     }
1813 dl 1.57 return count;
1814     }
1815    
1816     /**
1817 dl 1.1 * Returns a string identifying this pool, as well as its state,
1818     * including indications of run state, parallelism level, and
1819     * worker and task counts.
1820     *
1821     * @return a string identifying this pool, as well as its state
1822     */
1823     public String toString() {
1824     long st = getStealCount();
1825     long qt = getQueuedTaskCount();
1826     long qs = getQueuedSubmissionCount();
1827 dl 1.53 int pc = parallelism;
1828 dl 1.91 long c = ctl;
1829     int tc = pc + (short)(c >>> TC_SHIFT);
1830     int rc = pc + (int)(c >> AC_SHIFT);
1831     if (rc < 0) // ignore transient negative
1832     rc = 0;
1833     int ac = rc + blockedCount;
1834     String level;
1835     if ((c & STOP_BIT) != 0)
1836     level = (tc == 0)? "Terminated" : "Terminating";
1837     else
1838     level = shutdown? "Shutting down" : "Running";
1839 dl 1.1 return super.toString() +
1840 dl 1.91 "[" + level +
1841 dl 1.53 ", parallelism = " + pc +
1842     ", size = " + tc +
1843     ", active = " + ac +
1844     ", running = " + rc +
1845 dl 1.1 ", steals = " + st +
1846     ", tasks = " + qt +
1847     ", submissions = " + qs +
1848     "]";
1849     }
1850    
1851     /**
1852     * Initiates an orderly shutdown in which previously submitted
1853     * tasks are executed, but no new tasks will be accepted.
1854     * Invocation has no additional effect if already shut down.
1855     * Tasks that are in the process of being submitted concurrently
1856     * during the course of this method may or may not be rejected.
1857 jsr166 1.17 *
1858 dl 1.1 * @throws SecurityException if a security manager exists and
1859     * the caller is not permitted to modify threads
1860     * because it does not hold {@link
1861 jsr166 1.17 * java.lang.RuntimePermission}{@code ("modifyThread")}
1862 dl 1.1 */
1863     public void shutdown() {
1864     checkPermission();
1865 dl 1.91 shutdown = true;
1866 dl 1.53 tryTerminate(false);
1867 dl 1.1 }
1868    
1869     /**
1870 dl 1.42 * Attempts to cancel and/or stop all tasks, and reject all
1871     * subsequently submitted tasks. Tasks that are in the process of
1872     * being submitted or executed concurrently during the course of
1873     * this method may or may not be rejected. This method cancels
1874     * both existing and unexecuted tasks, in order to permit
1875     * termination in the presence of task dependencies. So the method
1876     * always returns an empty list (unlike the case for some other
1877     * Executors).
1878 jsr166 1.17 *
1879 dl 1.1 * @return an empty list
1880     * @throws SecurityException if a security manager exists and
1881     * the caller is not permitted to modify threads
1882     * because it does not hold {@link
1883 jsr166 1.17 * java.lang.RuntimePermission}{@code ("modifyThread")}
1884 dl 1.1 */
1885     public List<Runnable> shutdownNow() {
1886     checkPermission();
1887 dl 1.91 shutdown = true;
1888 dl 1.53 tryTerminate(true);
1889 dl 1.1 return Collections.emptyList();
1890     }
1891    
1892     /**
1893 jsr166 1.16 * Returns {@code true} if all tasks have completed following shut down.
1894 dl 1.1 *
1895 jsr166 1.16 * @return {@code true} if all tasks have completed following shut down
1896 dl 1.1 */
1897     public boolean isTerminated() {
1898 dl 1.91 long c = ctl;
1899     return ((c & STOP_BIT) != 0L &&
1900     (short)(c >>> TC_SHIFT) == -parallelism);
1901 dl 1.1 }
1902    
1903     /**
1904 jsr166 1.16 * Returns {@code true} if the process of termination has
1905 dl 1.42 * commenced but not yet completed. This method may be useful for
1906     * debugging. A return of {@code true} reported a sufficient
1907     * period after shutdown may indicate that submitted tasks have
1908 dl 1.88 * ignored or suppressed interruption, or are waiting for IO,
1909     * causing this executor not to properly terminate. (See the
1910     * advisory notes for class {@link ForkJoinTask} stating that
1911     * tasks should not normally entail blocking operations. But if
1912     * they do, they must abort them on interrupt.)
1913 dl 1.1 *
1914 dl 1.42 * @return {@code true} if terminating but not yet terminated
1915 dl 1.1 */
1916     public boolean isTerminating() {
1917 dl 1.91 long c = ctl;
1918     return ((c & STOP_BIT) != 0L &&
1919     (short)(c >>> TC_SHIFT) != -parallelism);
1920 dl 1.1 }
1921    
1922     /**
1923 dl 1.80 * Returns true if terminating or terminated. Used by ForkJoinWorkerThread.
1924     */
1925     final boolean isAtLeastTerminating() {
1926 dl 1.91 return (ctl & STOP_BIT) != 0L;
1927 dl 1.80 }
1928 jsr166 1.81
1929 dl 1.80 /**
1930 jsr166 1.16 * Returns {@code true} if this pool has been shut down.
1931 dl 1.1 *
1932 jsr166 1.16 * @return {@code true} if this pool has been shut down
1933 dl 1.1 */
1934     public boolean isShutdown() {
1935 dl 1.91 return shutdown;
1936 dl 1.42 }
1937    
1938     /**
1939 dl 1.1 * Blocks until all tasks have completed execution after a shutdown
1940     * request, or the timeout occurs, or the current thread is
1941     * interrupted, whichever happens first.
1942     *
1943     * @param timeout the maximum time to wait
1944     * @param unit the time unit of the timeout argument
1945 jsr166 1.16 * @return {@code true} if this executor terminated and
1946     * {@code false} if the timeout elapsed before termination
1947 dl 1.1 * @throws InterruptedException if interrupted while waiting
1948     */
1949     public boolean awaitTermination(long timeout, TimeUnit unit)
1950     throws InterruptedException {
1951 dl 1.91 long nanos = unit.toNanos(timeout);
1952     final ReentrantLock lock = this.submissionLock;
1953     lock.lock();
1954 dl 1.57 try {
1955 dl 1.91 for (;;) {
1956     if (isTerminated())
1957     return true;
1958     if (nanos <= 0)
1959     return false;
1960     nanos = termination.awaitNanos(nanos);
1961     }
1962     } finally {
1963     lock.unlock();
1964 dl 1.57 }
1965 dl 1.1 }
1966    
1967     /**
1968     * Interface for extending managed parallelism for tasks running
1969 jsr166 1.35 * in {@link ForkJoinPool}s.
1970     *
1971 dl 1.61 * <p>A {@code ManagedBlocker} provides two methods. Method
1972     * {@code isReleasable} must return {@code true} if blocking is
1973     * not necessary. Method {@code block} blocks the current thread
1974     * if necessary (perhaps internally invoking {@code isReleasable}
1975 dl 1.93 * before actually blocking). These actions are performed by any
1976     * thread invoking {@link ForkJoinPool#managedBlock}. The
1977     * unusual methods in this API accommodate synchronizers that may,
1978     * but don't usually, block for long periods. Similarly, they
1979     * allow more efficient internal handling of cases in which
1980     * additional workers may be, but usually are not, needed to
1981     * ensure sufficient parallelism. Toward this end,
1982     * implementations of method {@code isReleasable} must be amenable
1983     * to repeated invocation.
1984 jsr166 1.17 *
1985 dl 1.1 * <p>For example, here is a ManagedBlocker based on a
1986     * ReentrantLock:
1987 jsr166 1.17 * <pre> {@code
1988     * class ManagedLocker implements ManagedBlocker {
1989     * final ReentrantLock lock;
1990     * boolean hasLock = false;
1991     * ManagedLocker(ReentrantLock lock) { this.lock = lock; }
1992     * public boolean block() {
1993     * if (!hasLock)
1994     * lock.lock();
1995     * return true;
1996     * }
1997     * public boolean isReleasable() {
1998     * return hasLock || (hasLock = lock.tryLock());
1999 dl 1.1 * }
2000 jsr166 1.17 * }}</pre>
2001 dl 1.61 *
2002     * <p>Here is a class that possibly blocks waiting for an
2003     * item on a given queue:
2004     * <pre> {@code
2005     * class QueueTaker<E> implements ManagedBlocker {
2006     * final BlockingQueue<E> queue;
2007     * volatile E item = null;
2008     * QueueTaker(BlockingQueue<E> q) { this.queue = q; }
2009     * public boolean block() throws InterruptedException {
2010     * if (item == null)
2011 dl 1.65 * item = queue.take();
2012 dl 1.61 * return true;
2013     * }
2014     * public boolean isReleasable() {
2015 dl 1.65 * return item != null || (item = queue.poll()) != null;
2016 dl 1.61 * }
2017     * public E getItem() { // call after pool.managedBlock completes
2018     * return item;
2019     * }
2020     * }}</pre>
2021 dl 1.1 */
2022     public static interface ManagedBlocker {
2023     /**
2024     * Possibly blocks the current thread, for example waiting for
2025     * a lock or condition.
2026 jsr166 1.17 *
2027 jsr166 1.28 * @return {@code true} if no additional blocking is necessary
2028     * (i.e., if isReleasable would return true)
2029 dl 1.1 * @throws InterruptedException if interrupted while waiting
2030 jsr166 1.17 * (the method is not required to do so, but is allowed to)
2031 dl 1.1 */
2032     boolean block() throws InterruptedException;
2033    
2034     /**
2035 jsr166 1.28 * Returns {@code true} if blocking is unnecessary.
2036 dl 1.1 */
2037     boolean isReleasable();
2038     }
2039    
2040     /**
2041     * Blocks in accord with the given blocker. If the current thread
2042 jsr166 1.38 * is a {@link ForkJoinWorkerThread}, this method possibly
2043     * arranges for a spare thread to be activated if necessary to
2044 dl 1.57 * ensure sufficient parallelism while the current thread is blocked.
2045 jsr166 1.38 *
2046     * <p>If the caller is not a {@link ForkJoinTask}, this method is
2047     * behaviorally equivalent to
2048 jsr166 1.17 * <pre> {@code
2049     * while (!blocker.isReleasable())
2050     * if (blocker.block())
2051     * return;
2052     * }</pre>
2053 jsr166 1.38 *
2054     * If the caller is a {@code ForkJoinTask}, then the pool may
2055     * first be expanded to ensure parallelism, and later adjusted.
2056 dl 1.1 *
2057     * @param blocker the blocker
2058 jsr166 1.16 * @throws InterruptedException if blocker.block did so
2059 dl 1.1 */
2060 dl 1.57 public static void managedBlock(ManagedBlocker blocker)
2061 dl 1.1 throws InterruptedException {
2062     Thread t = Thread.currentThread();
2063 dl 1.61 if (t instanceof ForkJoinWorkerThread) {
2064     ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
2065     w.pool.awaitBlocker(blocker);
2066     }
2067 dl 1.57 else {
2068     do {} while (!blocker.isReleasable() && !blocker.block());
2069     }
2070 dl 1.1 }
2071    
2072 dl 1.33 // AbstractExecutorService overrides. These rely on undocumented
2073     // fact that ForkJoinTask.adapt returns ForkJoinTasks that also
2074     // implement RunnableFuture.
2075 dl 1.2
2076     protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
2077 jsr166 1.34 return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
2078 dl 1.2 }
2079    
2080     protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
2081 jsr166 1.34 return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
2082 dl 1.2 }
2083    
2084 jsr166 1.27 // Unsafe mechanics
2085 dl 1.91 private static final sun.misc.Unsafe UNSAFE;
2086     private static final long ctlOffset;
2087     private static final long stealCountOffset;
2088     private static final long blockedCountOffset;
2089     private static final long quiescerCountOffset;
2090     private static final long scanGuardOffset;
2091     private static final long nextWorkerNumberOffset;
2092     private static final long ABASE;
2093     private static final int ASHIFT;
2094    
2095     static {
2096     poolNumberGenerator = new AtomicInteger();
2097     workerSeedGenerator = new Random();
2098     modifyThreadPermission = new RuntimePermission("modifyThread");
2099     defaultForkJoinWorkerThreadFactory =
2100     new DefaultForkJoinWorkerThreadFactory();
2101     int s;
2102 jsr166 1.27 try {
2103 dl 1.91 UNSAFE = getUnsafe();
2104     Class k = ForkJoinPool.class;
2105     ctlOffset = UNSAFE.objectFieldOffset
2106     (k.getDeclaredField("ctl"));
2107     stealCountOffset = UNSAFE.objectFieldOffset
2108     (k.getDeclaredField("stealCount"));
2109     blockedCountOffset = UNSAFE.objectFieldOffset
2110     (k.getDeclaredField("blockedCount"));
2111     quiescerCountOffset = UNSAFE.objectFieldOffset
2112     (k.getDeclaredField("quiescerCount"));
2113     scanGuardOffset = UNSAFE.objectFieldOffset
2114     (k.getDeclaredField("scanGuard"));
2115     nextWorkerNumberOffset = UNSAFE.objectFieldOffset
2116     (k.getDeclaredField("nextWorkerNumber"));
2117     Class a = ForkJoinTask[].class;
2118     ABASE = UNSAFE.arrayBaseOffset(a);
2119     s = UNSAFE.arrayIndexScale(a);
2120     } catch (Exception e) {
2121     throw new Error(e);
2122     }
2123     if ((s & (s-1)) != 0)
2124     throw new Error("data type scale not a power of two");
2125     ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
2126 jsr166 1.27 }
2127    
2128     /**
2129     * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
2130     * Replace with a simple call to Unsafe.getUnsafe when integrating
2131     * into a jdk.
2132     *
2133     * @return a sun.misc.Unsafe
2134     */
2135     private static sun.misc.Unsafe getUnsafe() {
2136     try {
2137     return sun.misc.Unsafe.getUnsafe();
2138     } catch (SecurityException se) {
2139     try {
2140     return java.security.AccessController.doPrivileged
2141     (new java.security
2142     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
2143     public sun.misc.Unsafe run() throws Exception {
2144     java.lang.reflect.Field f = sun.misc
2145     .Unsafe.class.getDeclaredField("theUnsafe");
2146     f.setAccessible(true);
2147     return (sun.misc.Unsafe) f.get(null);
2148     }});
2149     } catch (java.security.PrivilegedActionException e) {
2150     throw new RuntimeException("Could not initialize intrinsics",
2151     e.getCause());
2152     }
2153     }
2154     }
2155 dl 1.1 }