ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinPool.java
Revision: 1.56
Committed: Thu May 27 16:46:48 2010 UTC (13 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.55: +315 -234 lines
Log Message:
Adaptive spins for joins; streamline call paths

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 dl 1.1 import java.util.concurrent.*;
10 jsr166 1.22
11     import java.util.ArrayList;
12     import java.util.Arrays;
13     import java.util.Collection;
14     import java.util.Collections;
15     import java.util.List;
16     import java.util.concurrent.locks.LockSupport;
17     import java.util.concurrent.locks.ReentrantLock;
18     import java.util.concurrent.atomic.AtomicInteger;
19 dl 1.53 import java.util.concurrent.CountDownLatch;
20 dl 1.1
21     /**
22 jsr166 1.29 * An {@link ExecutorService} for running {@link ForkJoinTask}s.
23 jsr166 1.39 * A {@code ForkJoinPool} provides the entry point for submissions
24     * from non-{@code ForkJoinTask}s, as well as management and
25 jsr166 1.48 * monitoring operations.
26 dl 1.1 *
27 dl 1.42 * <p>A {@code ForkJoinPool} differs from other kinds of {@link
28     * ExecutorService} mainly by virtue of employing
29     * <em>work-stealing</em>: all threads in the pool attempt to find and
30     * execute subtasks created by other active tasks (eventually blocking
31     * waiting for work if none exist). This enables efficient processing
32     * when most tasks spawn other subtasks (as do most {@code
33     * ForkJoinTask}s). A {@code ForkJoinPool} may also be used for mixed
34     * execution of some plain {@code Runnable}- or {@code Callable}-
35     * based activities along with {@code ForkJoinTask}s. When setting
36     * {@linkplain #setAsyncMode async mode}, a {@code ForkJoinPool} may
37     * also be appropriate for use with fine-grained tasks of any form
38     * that are never joined. Otherwise, other {@code ExecutorService}
39     * implementations are typically more appropriate choices.
40 dl 1.1 *
41 dl 1.42 * <p>A {@code ForkJoinPool} is constructed with a given target
42     * parallelism level; by default, equal to the number of available
43     * processors. Unless configured otherwise via {@link
44     * #setMaintainsParallelism}, the pool attempts to maintain this
45     * number of active (or available) threads by dynamically adding,
46     * suspending, or resuming internal worker threads, even if some tasks
47 dl 1.44 * are stalled waiting to join others. However, no such adjustments
48     * are performed in the face of blocked IO or other unmanaged
49 jsr166 1.39 * synchronization. The nested {@link ManagedBlocker} interface
50     * enables extension of the kinds of synchronization accommodated.
51     * The target parallelism level may also be changed dynamically
52 dl 1.42 * ({@link #setParallelism}). The total number of threads may be
53     * limited using method {@link #setMaximumPoolSize}, in which case it
54     * may become possible for the activities of a pool to stall due to
55 dl 1.53 * the lack of available threads to process new tasks. When the pool
56     * is executing tasks, these and other configuration setting methods
57     * may only gradually affect actual pool sizes. It is normally best
58     * practice to invoke these methods only when the pool is known to be
59     * quiescent.
60 dl 1.1 *
61     * <p>In addition to execution and lifecycle control methods, this
62     * class provides status check methods (for example
63 jsr166 1.29 * {@link #getStealCount}) that are intended to aid in developing,
64 dl 1.1 * tuning, and monitoring fork/join applications. Also, method
65 jsr166 1.29 * {@link #toString} returns indications of pool state in a
66 dl 1.2 * convenient form for informal monitoring.
67 dl 1.1 *
68 dl 1.42 * <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is
69     * used for all parallel task execution in a program or subsystem.
70     * Otherwise, use would not usually outweigh the construction and
71     * bookkeeping overhead of creating a large set of threads. For
72 jsr166 1.43 * example, a common pool could be used for the {@code SortTasks}
73 dl 1.42 * illustrated in {@link RecursiveAction}. Because {@code
74     * ForkJoinPool} uses threads in {@linkplain java.lang.Thread#isDaemon
75 jsr166 1.43 * daemon} mode, there is typically no need to explicitly {@link
76 dl 1.42 * #shutdown} such a pool upon program exit.
77     *
78     * <pre>
79     * static final ForkJoinPool mainPool = new ForkJoinPool();
80     * ...
81     * public void sort(long[] array) {
82     * mainPool.invoke(new SortTask(array, 0, array.length));
83     * }
84     * </pre>
85     *
86 dl 1.1 * <p><b>Implementation notes</b>: This implementation restricts the
87 dl 1.2 * maximum number of running threads to 32767. Attempts to create
88 jsr166 1.48 * pools with greater than the maximum number result in
89 jsr166 1.39 * {@code IllegalArgumentException}.
90 jsr166 1.16 *
91 jsr166 1.48 * <p>This implementation rejects submitted tasks (that is, by throwing
92     * {@link RejectedExecutionException}) only when the pool is shut down.
93     *
94 jsr166 1.16 * @since 1.7
95     * @author Doug Lea
96 dl 1.1 */
97 dl 1.2 public class ForkJoinPool extends AbstractExecutorService {
98 dl 1.1
99     /*
100 dl 1.53 * Implementation Overview
101     *
102     * This class provides the central bookkeeping and control for a
103     * set of worker threads: Submissions from non-FJ threads enter
104     * into a submission queue. Workers take these tasks and typically
105     * split them into subtasks that may be stolen by other workers.
106     * The main work-stealing mechanics implemented in class
107     * ForkJoinWorkerThread give first priority to processing tasks
108     * from their own queues (LIFO or FIFO, depending on mode), then
109     * to randomized FIFO steals of tasks in other worker queues, and
110     * lastly to new submissions. These mechanics do not consider
111     * affinities, loads, cache localities, etc, so rarely provide the
112     * best possible performance on a given machine, but portably
113     * provide good throughput by averaging over these factors.
114     * (Further, even if we did try to use such information, we do not
115     * usually have a basis for exploiting it. For example, some sets
116     * of tasks profit from cache affinities, but others are harmed by
117     * cache pollution effects.)
118     *
119     * The main throughput advantages of work-stealing stem from
120     * decentralized control -- workers mostly steal tasks from each
121     * other. We do not want to negate this by creating bottlenecks
122     * implementing the management responsibilities of this class. So
123     * we use a collection of techniques that avoid, reduce, or cope
124     * well with contention. These entail several instances of
125     * bit-packing into CASable fields to maintain only the minimally
126     * required atomicity. To enable such packing, we restrict maximum
127     * parallelism to (1<<15)-1 (enabling twice this to fit into a 16
128     * bit field), which is far in excess of normal operating range.
129     * Even though updates to some of these bookkeeping fields do
130     * sometimes contend with each other, they don't normally
131     * cache-contend with updates to others enough to warrant memory
132     * padding or isolation. So they are all held as fields of
133     * ForkJoinPool objects. The main capabilities are as follows:
134     *
135     * 1. Creating and removing workers. Workers are recorded in the
136     * "workers" array. This is an array as opposed to some other data
137     * structure to support index-based random steals by workers.
138     * Updates to the array recording new workers and unrecording
139     * terminated ones are protected from each other by a lock
140     * (workerLock) but the array is otherwise concurrently readable,
141     * and accessed directly by workers. To simplify index-based
142     * operations, the array size is always a power of two, and all
143 dl 1.56 * readers must tolerate null slots. Currently, all worker thread
144     * creation is on-demand, triggered by task submissions,
145     * replacement of terminated workers, and/or compensation for
146     * blocked workers. However, all other support code is set up to
147     * work with other policies.
148 dl 1.53 *
149     * 2. Bookkeeping for dynamically adding and removing workers. We
150     * maintain a given level of parallelism (or, if
151     * maintainsParallelism is false, at least avoid starvation). When
152     * some workers are known to be blocked (on joins or via
153     * ManagedBlocker), we may create or resume others to take their
154     * place until they unblock (see below). Implementing this
155     * requires counts of the number of "running" threads (i.e., those
156     * that are neither blocked nor artifically suspended) as well as
157     * the total number. These two values are packed into one field,
158     * "workerCounts" because we need accurate snapshots when deciding
159     * to create, resume or suspend. To support these decisions,
160 dl 1.56 * updates to spare counts must be prospective (not
161     * retrospective). For example, the running count is decremented
162     * before blocking by a thread about to block as a spare, but
163     * incremented by the thread about to unblock it. Updates upon
164     * resumption ofr threads blocking in awaitJoin or awaitBlocker
165     * cannot usually be prospective, so the running count is in
166     * general an upper bound of the number of productively running
167     * threads Updates to the workerCounts field sometimes transiently
168     * encounter a fair amount of contention when join dependencies
169     * are such that many threads block or unblock at about the same
170     * time. We alleviate this by sometimes bundling updates (for
171     * example blocking one thread on join and resuming a spare cancel
172     * each other out), and in most other cases performing an
173     * alternative action like releasing waiters or locating spares.
174 dl 1.53 *
175     * 3. Maintaining global run state. The run state of the pool
176     * consists of a runLevel (SHUTDOWN, TERMINATING, etc) similar to
177     * those in other Executor implementations, as well as a count of
178     * "active" workers -- those that are, or soon will be, or
179     * recently were executing tasks. The runLevel and active count
180     * are packed together in order to correctly trigger shutdown and
181     * termination. Without care, active counts can be subject to very
182     * high contention. We substantially reduce this contention by
183     * relaxing update rules. A worker must claim active status
184     * prospectively, by activating if it sees that a submitted or
185     * stealable task exists (it may find after activating that the
186     * task no longer exists). It stays active while processing this
187     * task (if it exists) and any other local subtasks it produces,
188     * until it cannot find any other tasks. It then tries
189     * inactivating (see method preStep), but upon update contention
190     * instead scans for more tasks, later retrying inactivation if it
191     * doesn't find any.
192     *
193     * 4. Managing idle workers waiting for tasks. We cannot let
194     * workers spin indefinitely scanning for tasks when none are
195     * available. On the other hand, we must quickly prod them into
196     * action when new tasks are submitted or generated. We
197     * park/unpark these idle workers using an event-count scheme.
198     * Field eventCount is incremented upon events that may enable
199     * workers that previously could not find a task to now find one:
200     * Submission of a new task to the pool, or another worker pushing
201     * a task onto a previously empty queue. (We also use this
202     * mechanism for termination and reconfiguration actions that
203     * require wakeups of idle workers). Each worker maintains its
204     * last known event count, and blocks when a scan for work did not
205     * find a task AND its lastEventCount matches the current
206     * eventCount. Waiting idle workers are recorded in a variant of
207     * Treiber stack headed by field eventWaiters which, when nonzero,
208     * encodes the thread index and count awaited for by the worker
209     * thread most recently calling eventSync. This thread in turn has
210     * a record (field nextEventWaiter) for the next waiting worker.
211     * In addition to allowing simpler decisions about need for
212     * wakeup, the event count bits in eventWaiters serve the role of
213     * tags to avoid ABA errors in Treiber stacks. To reduce delays
214     * in task diffusion, workers not otherwise occupied may invoke
215     * method releaseWaiters, that removes and signals (unparks)
216     * workers not waiting on current count. To minimize task
217     * production stalls associate with signalling, any worker pushing
218     * a task on an empty queue invokes the weaker method signalWork,
219     * that only releases idle workers until it detects interference
220     * by other threads trying to release, and lets them take
221     * over. The net effect is a tree-like diffusion of signals, where
222 dl 1.56 * released threads (and possibly others) help with unparks. To
223 dl 1.53 * further reduce contention effects a bit, failed CASes to
224     * increment field eventCount are tolerated without retries.
225     * Conceptually they are merged into the same event, which is OK
226     * when their only purpose is to enable workers to scan for work.
227     *
228     * 5. Managing suspension of extra workers. When a worker is about
229     * to block waiting for a join (or via ManagedBlockers), we may
230     * create a new thread to maintain parallelism level, or at least
231     * avoid starvation (see below). Usually, extra threads are needed
232     * for only very short periods, yet join dependencies are such
233     * that we sometimes need them in bursts. Rather than create new
234     * threads each time this happens, we suspend no-longer-needed
235     * extra ones as "spares". For most purposes, we don't distinguish
236     * "extra" spare threads from normal "core" threads: On each call
237     * to preStep (the only point at which we can do this) a worker
238     * checks to see if there are now too many running workers, and if
239 dl 1.56 * so, suspends itself. Methods awaitJoin and awaitBlocker look
240     * for suspended threads to resume before considering creating a
241     * new replacement. We don't need a special data structure to
242     * maintain spares; simply scanning the workers array looking for
243 dl 1.53 * worker.isSuspended() is fine because the calling thread is
244     * otherwise not doing anything useful anyway; we are at least as
245     * happy if after locating a spare, the caller doesn't actually
246     * block because the join is ready before we try to adjust and
247     * compensate. Note that this is intrinsically racy. One thread
248     * may become a spare at about the same time as another is
249     * needlessly being created. We counteract this and related slop
250     * in part by requiring resumed spares to immediately recheck (in
251     * preStep) to see whether they they should re-suspend. The only
252     * effective difference between "extra" and "core" threads is that
253     * we allow the "extra" ones to time out and die if they are not
254     * resumed within a keep-alive interval of a few seconds. This is
255     * implemented mainly within ForkJoinWorkerThread, but requires
256     * some coordination (isTrimmed() -- meaning killed while
257     * suspended) to correctly maintain pool counts.
258     *
259     * 6. Deciding when to create new workers. The main dynamic
260     * control in this class is deciding when to create extra threads,
261 dl 1.56 * in methods awaitJoin and awaitBlocker. We always
262     * need to create one when the number of running threads becomes
263     * zero. But because blocked joins are typically dependent, we
264     * don't necessarily need or want one-to-one replacement. Using a
265     * one-to-one compensation rule often leads to enough useless
266     * overhead creating, suspending, resuming, and/or killing threads
267     * to signficantly degrade throughput. We use a rule reflecting
268     * the idea that, the more spare threads you already have, the
269     * more evidence you need to create another one. The "evidence"
270     * here takes two forms: (1) Using a creation threshold expressed
271     * in terms of the current deficit -- target minus running
272 dl 1.53 * threads. To reduce flickering and drift around target values,
273     * the relation is quadratic: adding a spare if (dc*dc)>=(sc*pc)
274     * (where dc is deficit, sc is number of spare threads and pc is
275 dl 1.56 * target parallelism.) (2) Using a form of adaptive
276     * spionning. requiring a number of threshold checks proportional
277     * to the number of spare threads. This effectively reduces churn
278     * at the price of systematically undershooting target parallelism
279     * when many threads are blocked. However, biasing toward
280     * undeshooting partially compensates for the above mechanics to
281     * suspend extra threads, that normally lead to overshoot because
282     * we can only suspend workers in-between top-level actions. It
283     * also better copes with the fact that some of the methods in
284     * this class tend to never become compiled (but are interpreted),
285     * so some components of the entire set of controls might execute
286     * many times faster than others. And similarly for cases where
287     * the apparent lack of work is just due to GC stalls and other
288 dl 1.53 * transient system activity.
289     *
290     * 7. Maintaining other configuration parameters and monitoring
291     * statistics. Updates to fields controlling parallelism level,
292     * max size, etc can only meaningfully take effect for individual
293     * threads upon their next top-level actions; i.e., between
294     * stealing/running tasks/submission, which are separated by calls
295     * to preStep. Memory ordering for these (assumed infrequent)
296     * reconfiguration calls is ensured by using reads and writes to
297     * volatile field workerCounts (that must be read in preStep anyway)
298     * as "fences" -- user-level reads are preceded by reads of
299     * workCounts, and writes are followed by no-op CAS to
300     * workerCounts. The values reported by other management and
301     * monitoring methods are either computed on demand, or are kept
302     * in fields that are only updated when threads are otherwise
303     * idle.
304     *
305     * Beware that there is a lot of representation-level coupling
306     * among classes ForkJoinPool, ForkJoinWorkerThread, and
307     * ForkJoinTask. For example, direct access to "workers" array by
308     * workers, and direct access to ForkJoinTask.status by both
309     * ForkJoinPool and ForkJoinWorkerThread. There is little point
310     * trying to reduce this, since any associated future changes in
311     * representations will need to be accompanied by algorithmic
312     * changes anyway.
313     *
314     * Style notes: There are lots of inline assignments (of form
315     * "while ((local = field) != 0)") which are usually the simplest
316     * way to ensure read orderings. Also several occurrences of the
317     * unusual "do {} while(!cas...)" which is the simplest way to
318     * force an update of a CAS'ed variable. There are also a few
319     * other coding oddities that help some methods perform reasonably
320     * even when interpreted (not compiled).
321     *
322     * The order of declarations in this file is: (1) statics (2)
323     * fields (along with constants used when unpacking some of them)
324     * (3) internal control methods (4) callbacks and other support
325     * for ForkJoinTask and ForkJoinWorkerThread classes, (5) exported
326     * methods (plus a few little helpers).
327 dl 1.1 */
328    
329     /**
330 jsr166 1.35 * Factory for creating new {@link ForkJoinWorkerThread}s.
331     * A {@code ForkJoinWorkerThreadFactory} must be defined and used
332     * for {@code ForkJoinWorkerThread} subclasses that extend base
333     * functionality or initialize threads with different contexts.
334 dl 1.1 */
335     public static interface ForkJoinWorkerThreadFactory {
336     /**
337     * Returns a new worker thread operating in the given pool.
338     *
339     * @param pool the pool this thread works in
340 jsr166 1.48 * @throws NullPointerException if the pool is null
341 dl 1.1 */
342     public ForkJoinWorkerThread newThread(ForkJoinPool pool);
343     }
344    
345     /**
346 jsr166 1.17 * Default ForkJoinWorkerThreadFactory implementation; creates a
347 dl 1.1 * new ForkJoinWorkerThread.
348     */
349 dl 1.2 static class DefaultForkJoinWorkerThreadFactory
350 dl 1.1 implements ForkJoinWorkerThreadFactory {
351     public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
352 dl 1.53 return new ForkJoinWorkerThread(pool);
353 dl 1.1 }
354     }
355    
356     /**
357 dl 1.2 * Creates a new ForkJoinWorkerThread. This factory is used unless
358     * overridden in ForkJoinPool constructors.
359 dl 1.1 */
360 dl 1.2 public static final ForkJoinWorkerThreadFactory
361 dl 1.1 defaultForkJoinWorkerThreadFactory =
362     new DefaultForkJoinWorkerThreadFactory();
363    
364     /**
365     * Permission required for callers of methods that may start or
366     * kill threads.
367     */
368     private static final RuntimePermission modifyThreadPermission =
369     new RuntimePermission("modifyThread");
370    
371     /**
372     * If there is a security manager, makes sure caller has
373     * permission to modify threads.
374     */
375     private static void checkPermission() {
376     SecurityManager security = System.getSecurityManager();
377     if (security != null)
378     security.checkPermission(modifyThreadPermission);
379     }
380    
381     /**
382     * Generator for assigning sequence numbers as pool names.
383     */
384     private static final AtomicInteger poolNumberGenerator =
385     new AtomicInteger();
386    
387     /**
388 dl 1.53 * Absolute bound for parallelism level. Twice this number must
389     * fit into a 16bit field to enable word-packing for some counts.
390     */
391     private static final int MAX_THREADS = 0x7fff;
392    
393     /**
394     * Array holding all worker threads in the pool. Array size must
395     * be a power of two. Updates and replacements are protected by
396     * workerLock, but the array is always kept in a consistent enough
397     * state to be randomly accessed without locking by workers
398     * performing work-stealing, as well as other traversal-based
399     * methods in this class. All readers must tolerate that some
400     * array slots may be null.
401 dl 1.1 */
402     volatile ForkJoinWorkerThread[] workers;
403    
404     /**
405 dl 1.53 * Queue for external submissions.
406 dl 1.1 */
407 dl 1.53 private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue;
408 dl 1.1
409     /**
410 dl 1.53 * Lock protecting updates to workers array.
411 dl 1.1 */
412 dl 1.53 private final ReentrantLock workerLock;
413 dl 1.1
414     /**
415 dl 1.53 * Latch released upon termination.
416 dl 1.1 */
417 dl 1.53 private final CountDownLatch terminationLatch;
418 dl 1.1
419     /**
420     * Creation factory for worker threads.
421     */
422     private final ForkJoinWorkerThreadFactory factory;
423    
424     /**
425 dl 1.53 * Sum of per-thread steal counts, updated only when threads are
426     * idle or terminating.
427 dl 1.1 */
428 dl 1.53 private volatile long stealCount;
429 dl 1.1
430     /**
431 dl 1.53 * Encoded record of top of treiber stack of threads waiting for
432     * events. The top 32 bits contain the count being waited for. The
433     * bottom word contains one plus the pool index of waiting worker
434     * thread.
435 dl 1.1 */
436 dl 1.53 private volatile long eventWaiters;
437    
438     private static final int EVENT_COUNT_SHIFT = 32;
439     private static final long WAITER_INDEX_MASK = (1L << EVENT_COUNT_SHIFT)-1L;
440 dl 1.1
441     /**
442 dl 1.53 * A counter for events that may wake up worker threads:
443     * - Submission of a new task to the pool
444     * - A worker pushing a task on an empty queue
445     * - termination and reconfiguration
446 dl 1.1 */
447 dl 1.53 private volatile int eventCount;
448    
449     /**
450     * Lifecycle control. The low word contains the number of workers
451     * that are (probably) executing tasks. This value is atomically
452     * incremented before a worker gets a task to run, and decremented
453     * when worker has no tasks and cannot find any. Bits 16-18
454     * contain runLevel value. When all are zero, the pool is
455     * running. Level transitions are monotonic (running -> shutdown
456     * -> terminating -> terminated) so each transition adds a bit.
457     * These are bundled together to ensure consistent read for
458     * termination checks (i.e., that runLevel is at least SHUTDOWN
459     * and active threads is zero).
460     */
461     private volatile int runState;
462    
463     // Note: The order among run level values matters.
464     private static final int RUNLEVEL_SHIFT = 16;
465     private static final int SHUTDOWN = 1 << RUNLEVEL_SHIFT;
466     private static final int TERMINATING = 1 << (RUNLEVEL_SHIFT + 1);
467     private static final int TERMINATED = 1 << (RUNLEVEL_SHIFT + 2);
468     private static final int ACTIVE_COUNT_MASK = (1 << RUNLEVEL_SHIFT) - 1;
469     private static final int ONE_ACTIVE = 1; // active update delta
470 dl 1.1
471     /**
472 dl 1.53 * Holds number of total (i.e., created and not yet terminated)
473     * and running (i.e., not blocked on joins or other managed sync)
474     * threads, packed together to ensure consistent snapshot when
475     * making decisions about creating and suspending spare
476     * threads. Updated only by CAS. Note that adding a new worker
477     * requires incrementing both counts, since workers start off in
478     * running state. This field is also used for memory-fencing
479     * configuration parameters.
480     */
481     private volatile int workerCounts;
482    
483     private static final int TOTAL_COUNT_SHIFT = 16;
484     private static final int RUNNING_COUNT_MASK = (1 << TOTAL_COUNT_SHIFT) - 1;
485     private static final int ONE_RUNNING = 1;
486     private static final int ONE_TOTAL = 1 << TOTAL_COUNT_SHIFT;
487    
488     /*
489 dl 1.56 * Fields parallelism. maxPoolSize, and maintainsParallelism are
490     * non-volatile, but external reads/writes use workerCount fences
491     * to ensure visability.
492 dl 1.1 */
493    
494     /**
495 dl 1.53 * The target parallelism level.
496 dl 1.1 */
497 dl 1.53 private int parallelism;
498 dl 1.1
499     /**
500 dl 1.53 * The maximum allowed pool size.
501 dl 1.1 */
502 dl 1.53 private int maxPoolSize;
503 dl 1.1
504     /**
505 dl 1.53 * True if use local fifo, not default lifo, for local polling
506     * Replicated by ForkJoinWorkerThreads
507 dl 1.1 */
508 dl 1.56 private volatile boolean locallyFifo;
509 dl 1.1
510     /**
511 dl 1.53 * Controls whether to add spares to maintain parallelism
512 dl 1.1 */
513 dl 1.53 private boolean maintainsParallelism;
514 dl 1.1
515     /**
516 dl 1.53 * The uncaught exception handler used when any worker
517     * abruptly terminates
518 dl 1.6 */
519 dl 1.56 private volatile Thread.UncaughtExceptionHandler ueh;
520 dl 1.6
521     /**
522 dl 1.53 * Pool number, just for assigning useful names to worker threads
523 dl 1.1 */
524 dl 1.53 private final int poolNumber;
525 dl 1.1
526 dl 1.53 // utilities for updating fields
527 dl 1.1
528     /**
529 dl 1.53 * Adds delta to running count. Used mainly by ForkJoinTask.
530 dl 1.1 */
531     final void updateRunningCount(int delta) {
532 dl 1.53 int wc;
533     do {} while (!UNSAFE.compareAndSwapInt(this, workerCountsOffset,
534     wc = workerCounts,
535     wc + delta));
536 dl 1.1 }
537    
538     /**
539 dl 1.56 * Decrements running count unless already zero
540     */
541     final boolean tryDecrementRunningCount() {
542     int wc = workerCounts;
543     if ((wc & RUNNING_COUNT_MASK) == 0)
544     return false;
545     return UNSAFE.compareAndSwapInt(this, workerCountsOffset,
546     wc, wc - ONE_RUNNING);
547     }
548    
549     /**
550 dl 1.53 * Write fence for user modifications of pool parameters
551     * (parallelism. etc). Note that it doesn't matter if CAS fails.
552 dl 1.1 */
553 dl 1.53 private void workerCountWriteFence() {
554     int wc;
555     UNSAFE.compareAndSwapInt(this, workerCountsOffset,
556     wc = workerCounts, wc);
557 dl 1.1 }
558    
559     /**
560 dl 1.53 * Read fence for external reads of pool parameters
561     * (parallelism. maxPoolSize, etc).
562     */
563     private void workerCountReadFence() {
564     int ignore = workerCounts;
565     }
566 dl 1.1
567     /**
568 jsr166 1.17 * Tries incrementing active count; fails on contention.
569 dl 1.53 * Called by workers before executing tasks.
570 jsr166 1.17 *
571 jsr166 1.16 * @return true on success
572 dl 1.1 */
573 dl 1.4 final boolean tryIncrementActiveCount() {
574 dl 1.53 int c;
575     return UNSAFE.compareAndSwapInt(this, runStateOffset,
576     c = runState, c + ONE_ACTIVE);
577 dl 1.1 }
578    
579     /**
580 jsr166 1.16 * Tries decrementing active count; fails on contention.
581 dl 1.53 * Called when workers cannot find tasks to run.
582     */
583     final boolean tryDecrementActiveCount() {
584     int c;
585     return UNSAFE.compareAndSwapInt(this, runStateOffset,
586     c = runState, c - ONE_ACTIVE);
587     }
588    
589     /**
590     * Advances to at least the given level. Returns true if not
591     * already in at least the given level.
592     */
593     private boolean advanceRunLevel(int level) {
594     for (;;) {
595     int s = runState;
596     if ((s & level) != 0)
597     return false;
598     if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, s | level))
599     return true;
600     }
601     }
602    
603     // workers array maintenance
604    
605     /**
606     * Records and returns a workers array index for new worker.
607     */
608     private int recordWorker(ForkJoinWorkerThread w) {
609     // Try using slot totalCount-1. If not available, scan and/or resize
610     int k = (workerCounts >>> TOTAL_COUNT_SHIFT) - 1;
611     final ReentrantLock lock = this.workerLock;
612     lock.lock();
613     try {
614     ForkJoinWorkerThread[] ws = workers;
615 dl 1.56 int nws = ws.length;
616     if (k < 0 || k >= nws || ws[k] != null) {
617     for (k = 0; k < nws && ws[k] != null; ++k)
618 dl 1.53 ;
619 dl 1.56 if (k == nws)
620     ws = Arrays.copyOf(ws, nws << 1);
621 dl 1.53 }
622     ws[k] = w;
623     workers = ws; // volatile array write ensures slot visibility
624     } finally {
625     lock.unlock();
626     }
627     return k;
628     }
629    
630     /**
631     * Nulls out record of worker in workers array
632     */
633     private void forgetWorker(ForkJoinWorkerThread w) {
634     int idx = w.poolIndex;
635     // Locking helps method recordWorker avoid unecessary expansion
636     final ReentrantLock lock = this.workerLock;
637     lock.lock();
638     try {
639     ForkJoinWorkerThread[] ws = workers;
640     if (idx >= 0 && idx < ws.length && ws[idx] == w) // verify
641     ws[idx] = null;
642     } finally {
643     lock.unlock();
644     }
645     }
646    
647     // adding and removing workers
648    
649     /**
650     * Tries to create and add new worker. Assumes that worker counts
651     * are already updated to accommodate the worker, so adjusts on
652     * failure.
653     *
654     * @return new worker or null if creation failed
655     */
656     private ForkJoinWorkerThread addWorker() {
657     ForkJoinWorkerThread w = null;
658     try {
659     w = factory.newThread(this);
660     } finally { // Adjust on either null or exceptional factory return
661     if (w == null) {
662     onWorkerCreationFailure();
663     return null;
664     }
665     }
666     w.start(recordWorker(w), locallyFifo, ueh);
667     return w;
668     }
669    
670     /**
671     * Adjusts counts upon failure to create worker
672     */
673     private void onWorkerCreationFailure() {
674 dl 1.56 for (;;) {
675     int wc = workerCounts;
676     if ((wc >>> TOTAL_COUNT_SHIFT) > 0 &&
677     UNSAFE.compareAndSwapInt(this, workerCountsOffset,
678     wc, wc - (ONE_RUNNING|ONE_TOTAL)))
679     break;
680     }
681 dl 1.53 tryTerminate(false); // in case of failure during shutdown
682     }
683    
684     /**
685     * Create enough total workers to establish target parallelism,
686     * giving up if terminating or addWorker fails
687     */
688     private void ensureEnoughTotalWorkers() {
689     int wc;
690 dl 1.56 while (((wc = workerCounts) >>> TOTAL_COUNT_SHIFT) < parallelism &&
691     runState < TERMINATING) {
692 dl 1.53 if ((UNSAFE.compareAndSwapInt(this, workerCountsOffset,
693     wc, wc + (ONE_RUNNING|ONE_TOTAL)) &&
694     addWorker() == null))
695     break;
696     }
697     }
698    
699     /**
700     * Final callback from terminating worker. Removes record of
701     * worker from array, and adjusts counts. If pool is shutting
702     * down, tries to complete terminatation, else possibly replaces
703     * the worker.
704     *
705     * @param w the worker
706     */
707     final void workerTerminated(ForkJoinWorkerThread w) {
708     if (w.active) { // force inactive
709     w.active = false;
710     do {} while (!tryDecrementActiveCount());
711     }
712     forgetWorker(w);
713    
714 dl 1.56 // Decrement total count, and if was running, running count
715     // Spin (waiting for other updates) if either would be negative
716     int nr = w.isTrimmed() ? 0 : ONE_RUNNING;
717     int unit = ONE_TOTAL + nr;
718     for (;;) {
719     int wc = workerCounts;
720     int rc = wc & RUNNING_COUNT_MASK;
721     if (rc - nr < 0 || (wc >>> TOTAL_COUNT_SHIFT) == 0)
722     Thread.yield(); // back off if waiting for other updates
723     else if (UNSAFE.compareAndSwapInt(this, workerCountsOffset,
724     wc, wc - unit))
725     break;
726     }
727 dl 1.53
728     accumulateStealCount(w); // collect final count
729     if (!tryTerminate(false))
730     ensureEnoughTotalWorkers();
731     }
732    
733     // Waiting for and signalling events
734    
735     /**
736     * Ensures eventCount on exit is different (mod 2^32) than on
737     * entry. CAS failures are OK -- any change in count suffices.
738     */
739     private void advanceEventCount() {
740     int c;
741     UNSAFE.compareAndSwapInt(this, eventCountOffset, c = eventCount, c+1);
742     }
743    
744     /**
745     * Releases workers blocked on a count not equal to current count.
746     */
747     final void releaseWaiters() {
748     long top;
749     int id;
750     while ((id = (int)((top = eventWaiters) & WAITER_INDEX_MASK)) > 0 &&
751     (int)(top >>> EVENT_COUNT_SHIFT) != eventCount) {
752     ForkJoinWorkerThread[] ws = workers;
753     ForkJoinWorkerThread w;
754     if (ws.length >= id && (w = ws[id - 1]) != null &&
755     UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
756     top, w.nextWaiter))
757     LockSupport.unpark(w);
758     }
759     }
760    
761     /**
762     * Advances eventCount and releases waiters until interference by
763     * other releasing threads is detected.
764     */
765     final void signalWork() {
766     int ec;
767     UNSAFE.compareAndSwapInt(this, eventCountOffset, ec=eventCount, ec+1);
768     outer:for (;;) {
769     long top = eventWaiters;
770     ec = eventCount;
771     for (;;) {
772     ForkJoinWorkerThread[] ws; ForkJoinWorkerThread w;
773     int id = (int)(top & WAITER_INDEX_MASK);
774     if (id <= 0 || (int)(top >>> EVENT_COUNT_SHIFT) == ec)
775     return;
776     if ((ws = workers).length < id || (w = ws[id - 1]) == null ||
777     !UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
778     top, top = w.nextWaiter))
779     continue outer; // possibly stale; reread
780     LockSupport.unpark(w);
781     if (top != eventWaiters) // let someone else take over
782     return;
783     }
784     }
785     }
786    
787     /**
788     * If worker is inactive, blocks until terminating or event count
789     * advances from last value held by worker; in any case helps
790     * release others.
791     *
792     * @param w the calling worker thread
793     */
794     private void eventSync(ForkJoinWorkerThread w) {
795     if (!w.active) {
796     int prev = w.lastEventCount;
797     long nextTop = (((long)prev << EVENT_COUNT_SHIFT) |
798     ((long)(w.poolIndex + 1)));
799     long top;
800     while ((runState < SHUTDOWN || !tryTerminate(false)) &&
801     (((int)(top = eventWaiters) & WAITER_INDEX_MASK) == 0 ||
802     (int)(top >>> EVENT_COUNT_SHIFT) == prev) &&
803     eventCount == prev) {
804     if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
805     w.nextWaiter = top, nextTop)) {
806     accumulateStealCount(w); // transfer steals while idle
807     Thread.interrupted(); // clear/ignore interrupt
808     while (eventCount == prev)
809     w.doPark();
810     break;
811     }
812     }
813     w.lastEventCount = eventCount;
814     }
815     releaseWaiters();
816     }
817    
818     /**
819     * Callback from workers invoked upon each top-level action (i.e.,
820     * stealing a task or taking a submission and running
821     * it). Performs one or both of the following:
822     *
823     * * If the worker cannot find work, updates its active status to
824     * inactive and updates activeCount unless there is contention, in
825     * which case it may try again (either in this or a subsequent
826     * call). Additionally, awaits the next task event and/or helps
827     * wake up other releasable waiters.
828 jsr166 1.17 *
829 dl 1.53 * * If there are too many running threads, suspends this worker
830     * (first forcing inactivation if necessary). If it is not
831     * resumed before a keepAlive elapses, the worker may be "trimmed"
832     * -- killed while suspended within suspendAsSpare. Otherwise,
833     * upon resume it rechecks to make sure that it is still needed.
834     *
835     * @param w the worker
836     * @param worked false if the worker scanned for work but didn't
837     * find any (in which case it may block waiting for work).
838     */
839     final void preStep(ForkJoinWorkerThread w, boolean worked) {
840     boolean active = w.active;
841     boolean inactivate = !worked & active;
842     for (;;) {
843     if (inactivate) {
844     int c = runState;
845     if (UNSAFE.compareAndSwapInt(this, runStateOffset,
846     c, c - ONE_ACTIVE))
847     inactivate = active = w.active = false;
848     }
849     int wc = workerCounts;
850     if ((wc & RUNNING_COUNT_MASK) <= parallelism) {
851     if (!worked)
852     eventSync(w);
853     return;
854     }
855     if (!(inactivate |= active) && // must inactivate to suspend
856     UNSAFE.compareAndSwapInt(this, workerCountsOffset,
857     wc, wc - ONE_RUNNING) &&
858     !w.suspendAsSpare()) // false if trimmed
859     return;
860     }
861     }
862    
863     /**
864     * Adjusts counts and creates or resumes compensating threads for
865 dl 1.56 * a worker blocking on task joinMe. First tries resuming an
866     * existing spare (which usually also avoids any count
867     * adjustment), but must then decrement running count to determine
868     * whether a new thread is needed. See above for fuller
869     * explanation. This code is sprawled out non-modularly mainly
870     * because adaptive spinning works best if the entire method is
871     * either interpreted or compiled vs having only some pieces of it
872     * compiled.
873     *
874     * @param joinMe the task to join
875     * @return task status on exit (to simplify usage by callers)
876 dl 1.53 */
877 dl 1.56 final int awaitJoin(ForkJoinTask<?> joinMe) {
878     int pc = parallelism;
879     boolean adj = false; // true when running count adjusted
880     int scans = 0;
881 dl 1.53
882 dl 1.56 while (joinMe.status >= 0) {
883 dl 1.53 ForkJoinWorkerThread spare = null;
884 dl 1.56 if ((workerCounts & RUNNING_COUNT_MASK) < pc) {
885     ForkJoinWorkerThread[] ws = workers;
886     int nws = ws.length;
887     for (int i = 0; i < nws; ++i) {
888     ForkJoinWorkerThread w = ws[i];
889     if (w != null && w.isSuspended()) {
890     spare = w;
891     break;
892     }
893     }
894     if (joinMe.status < 0)
895 dl 1.53 break;
896     }
897 dl 1.56 int wc = workerCounts;
898     int rc = wc & RUNNING_COUNT_MASK;
899     int dc = pc - rc;
900     if (dc > 0 && spare != null && spare.tryUnsuspend()) {
901     if (adj) {
902 dl 1.53 int c;
903 dl 1.56 do {} while (!UNSAFE.compareAndSwapInt
904     (this, workerCountsOffset,
905     c = workerCounts, c + ONE_RUNNING));
906     }
907     adj = true;
908 dl 1.53 LockSupport.unpark(spare);
909     }
910 dl 1.56 else if (adj) {
911     if (dc <= 0)
912     break;
913 dl 1.53 int tc = wc >>> TOTAL_COUNT_SHIFT;
914 dl 1.56 if (scans > tc) {
915     int ts = (tc - pc) * pc;
916     if (rc != 0 && (dc * dc < ts || !maintainsParallelism))
917     break;
918     if (scans > ts && tc < maxPoolSize &&
919     UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
920     wc+(ONE_RUNNING|ONE_TOTAL))){
921     addWorker();
922     break;
923     }
924 dl 1.53 }
925     }
926 dl 1.56 else if (rc != 0)
927     adj = UNSAFE.compareAndSwapInt (this, workerCountsOffset,
928     wc, wc - ONE_RUNNING);
929     if ((scans++ & 1) == 0)
930     releaseWaiters(); // help others progress
931     else
932     Thread.yield(); // avoid starving productive threads
933     }
934    
935     if (adj) {
936     joinMe.internalAwaitDone();
937     int c;
938     do {} while (!UNSAFE.compareAndSwapInt
939     (this, workerCountsOffset,
940     c = workerCounts, c + ONE_RUNNING));
941 dl 1.53 }
942 dl 1.56 return joinMe.status;
943 dl 1.53 }
944    
945     /**
946 dl 1.56 * Same idea as awaitJoin
947 dl 1.53 */
948 dl 1.56 final void awaitBlocker(ManagedBlocker blocker, boolean maintainPar)
949 dl 1.53 throws InterruptedException {
950 dl 1.56 maintainPar &= maintainsParallelism;
951     int pc = parallelism;
952     boolean adj = false; // true when running count adjusted
953     int scans = 0;
954     boolean done;
955    
956 dl 1.53 for (;;) {
957     if (done = blocker.isReleasable())
958     break;
959     ForkJoinWorkerThread spare = null;
960 dl 1.56 if ((workerCounts & RUNNING_COUNT_MASK) < pc) {
961     ForkJoinWorkerThread[] ws = workers;
962     int nws = ws.length;
963     for (int i = 0; i < nws; ++i) {
964     ForkJoinWorkerThread w = ws[i];
965     if (w != null && w.isSuspended()) {
966     spare = w;
967     break;
968     }
969     }
970     if (done = blocker.isReleasable())
971 dl 1.53 break;
972     }
973 dl 1.56 int wc = workerCounts;
974     int rc = wc & RUNNING_COUNT_MASK;
975     int dc = pc - rc;
976     if (dc > 0 && spare != null && spare.tryUnsuspend()) {
977     if (adj) {
978 dl 1.53 int c;
979 dl 1.56 do {} while (!UNSAFE.compareAndSwapInt
980     (this, workerCountsOffset,
981     c = workerCounts, c + ONE_RUNNING));
982 dl 1.53 }
983 dl 1.56 adj = true;
984 dl 1.53 LockSupport.unpark(spare);
985     }
986 dl 1.56 else if (adj) {
987     if (dc <= 0)
988     break;
989 dl 1.53 int tc = wc >>> TOTAL_COUNT_SHIFT;
990 dl 1.56 if (scans > tc) {
991     int ts = (tc - pc) * pc;
992     if (rc != 0 && (dc * dc < ts || !maintainPar))
993     break;
994     if (scans > ts && tc < maxPoolSize &&
995     UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
996     wc+(ONE_RUNNING|ONE_TOTAL))){
997     addWorker();
998     break;
999     }
1000 dl 1.53 }
1001     }
1002 dl 1.56 else if (rc != 0)
1003     adj = UNSAFE.compareAndSwapInt (this, workerCountsOffset,
1004     wc, wc - ONE_RUNNING);
1005     if ((++scans & 1) == 0)
1006     releaseWaiters(); // help others progress
1007     else
1008     Thread.yield(); // avoid starving productive threads
1009 dl 1.53 }
1010    
1011     try {
1012     if (!done)
1013     do {} while (!blocker.isReleasable() && !blocker.block());
1014     } finally {
1015 dl 1.56 if (adj) {
1016 dl 1.53 int c;
1017 dl 1.56 do {} while (!UNSAFE.compareAndSwapInt
1018     (this, workerCountsOffset,
1019     c = workerCounts, c + ONE_RUNNING));
1020 dl 1.53 }
1021     }
1022     }
1023    
1024     /**
1025 dl 1.54 * Unless there are not enough other running threads, adjusts
1026 dl 1.56 * counts and blocks a worker performing helpJoin that cannot find
1027     * any work.
1028 dl 1.54 *
1029 dl 1.56 * @return true if joinMe now done
1030 dl 1.54 */
1031 dl 1.56 final boolean tryAwaitBusyJoin(ForkJoinTask<?> joinMe) {
1032     int pc = parallelism;
1033     outer:for (;;) {
1034     releaseWaiters();
1035     if ((workerCounts & RUNNING_COUNT_MASK) < pc) {
1036     ForkJoinWorkerThread[] ws = workers;
1037     int nws = ws.length;
1038     for (int i = 0; i < nws; ++i) {
1039     ForkJoinWorkerThread w = ws[i];
1040 dl 1.54 if (w != null && w.isSuspended()) {
1041 dl 1.56 if (joinMe.status < 0)
1042     return true;
1043     if ((workerCounts & RUNNING_COUNT_MASK) > pc)
1044     break;
1045     if (w.tryUnsuspend()) {
1046     LockSupport.unpark(w);
1047     break outer;
1048 dl 1.54 }
1049 dl 1.56 continue outer;
1050 dl 1.54 }
1051     }
1052     }
1053 dl 1.56 if (joinMe.status < 0)
1054     return true;
1055     int wc = workerCounts;
1056     if ((wc & RUNNING_COUNT_MASK) <= 2 ||
1057     (wc >>> TOTAL_COUNT_SHIFT) < pc)
1058     return false; // keep this thread alive
1059 dl 1.54 if (UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1060 dl 1.56 wc, wc - ONE_RUNNING))
1061 dl 1.54 break;
1062     }
1063 dl 1.56
1064     joinMe.internalAwaitDone();
1065     int c;
1066     do {} while (!UNSAFE.compareAndSwapInt
1067     (this, workerCountsOffset,
1068     c = workerCounts, c + ONE_RUNNING));
1069     return true;
1070 dl 1.54 }
1071    
1072     /**
1073 dl 1.53 * Possibly initiates and/or completes termination.
1074     *
1075     * @param now if true, unconditionally terminate, else only
1076     * if shutdown and empty queue and no active workers
1077     * @return true if now terminating or terminated
1078 dl 1.1 */
1079 dl 1.53 private boolean tryTerminate(boolean now) {
1080     if (now)
1081     advanceRunLevel(SHUTDOWN); // ensure at least SHUTDOWN
1082     else if (runState < SHUTDOWN ||
1083     !submissionQueue.isEmpty() ||
1084     (runState & ACTIVE_COUNT_MASK) != 0)
1085 dl 1.4 return false;
1086 dl 1.53
1087     if (advanceRunLevel(TERMINATING))
1088     startTerminating();
1089    
1090     // Finish now if all threads terminated; else in some subsequent call
1091     if ((workerCounts >>> TOTAL_COUNT_SHIFT) == 0) {
1092     advanceRunLevel(TERMINATED);
1093     terminationLatch.countDown();
1094     }
1095 dl 1.4 return true;
1096 dl 1.1 }
1097    
1098     /**
1099 dl 1.53 * Actions on transition to TERMINATING
1100     */
1101     private void startTerminating() {
1102 dl 1.56 for (int i = 0; i < 2; ++i) { // twice to mop up newly created workers
1103     cancelSubmissions();
1104     shutdownWorkers();
1105     cancelWorkerTasks();
1106     advanceEventCount();
1107     releaseWaiters();
1108     interruptWorkers();
1109     }
1110     }
1111    
1112     /**
1113     * Clear out and cancel submissions, ignoring exceptions
1114     */
1115     private void cancelSubmissions() {
1116 dl 1.53 ForkJoinTask<?> task;
1117     while ((task = submissionQueue.poll()) != null) {
1118     try {
1119     task.cancel(false);
1120     } catch (Throwable ignore) {
1121     }
1122     }
1123 dl 1.56 }
1124    
1125     /**
1126     * Sets all worker run states to at least shutdown,
1127     * also resuming suspended workers
1128     */
1129     private void shutdownWorkers() {
1130     ForkJoinWorkerThread[] ws = workers;
1131     int nws = ws.length;
1132     for (int i = 0; i < nws; ++i) {
1133     ForkJoinWorkerThread w = ws[i];
1134 dl 1.53 if (w != null)
1135 dl 1.56 w.shutdown();
1136 dl 1.53 }
1137 dl 1.56 }
1138    
1139     /**
1140     * Clears out and cancels all locally queued tasks
1141     */
1142     private void cancelWorkerTasks() {
1143     ForkJoinWorkerThread[] ws = workers;
1144     int nws = ws.length;
1145     for (int i = 0; i < nws; ++i) {
1146     ForkJoinWorkerThread w = ws[i];
1147 dl 1.53 if (w != null)
1148     w.cancelTasks();
1149     }
1150 dl 1.56 }
1151    
1152     /**
1153     * Unsticks all workers blocked on joins etc
1154     */
1155     private void interruptWorkers() {
1156     ForkJoinWorkerThread[] ws = workers;
1157     int nws = ws.length;
1158     for (int i = 0; i < nws; ++i) {
1159     ForkJoinWorkerThread w = ws[i];
1160 dl 1.53 if (w != null && !w.isTerminated()) {
1161     try {
1162     w.interrupt();
1163     } catch (SecurityException ignore) {
1164     }
1165     }
1166     }
1167     }
1168    
1169     // misc support for ForkJoinWorkerThread
1170    
1171     /**
1172     * Returns pool number
1173 dl 1.1 */
1174 dl 1.53 final int getPoolNumber() {
1175     return poolNumber;
1176 dl 1.1 }
1177    
1178     /**
1179 dl 1.53 * Accumulates steal count from a worker, clearing
1180     * the worker's value
1181 dl 1.1 */
1182 dl 1.53 final void accumulateStealCount(ForkJoinWorkerThread w) {
1183     int sc = w.stealCount;
1184     if (sc != 0) {
1185     long c;
1186     w.stealCount = 0;
1187     do {} while (!UNSAFE.compareAndSwapLong(this, stealCountOffset,
1188     c = stealCount, c + sc));
1189 dl 1.1 }
1190     }
1191    
1192     /**
1193 dl 1.53 * Returns the approximate (non-atomic) number of idle threads per
1194     * active thread.
1195     */
1196     final int idlePerActive() {
1197     int ac = runState; // no mask -- artifically boosts during shutdown
1198     int pc = parallelism; // use targeted parallelism, not rc
1199     // Use exact results for small values, saturate past 4
1200     return pc <= ac? 0 : pc >>> 1 <= ac? 1 : pc >>> 2 <= ac? 3 : pc >>> 3;
1201     }
1202    
1203     // Public and protected methods
1204 dl 1.1
1205     // Constructors
1206    
1207     /**
1208 dl 1.42 * Creates a {@code ForkJoinPool} with parallelism equal to {@link
1209     * java.lang.Runtime#availableProcessors}, and using the {@linkplain
1210     * #defaultForkJoinWorkerThreadFactory default thread factory}.
1211 jsr166 1.17 *
1212 dl 1.1 * @throws SecurityException if a security manager exists and
1213     * the caller is not permitted to modify threads
1214     * because it does not hold {@link
1215 jsr166 1.17 * java.lang.RuntimePermission}{@code ("modifyThread")}
1216 dl 1.1 */
1217     public ForkJoinPool() {
1218     this(Runtime.getRuntime().availableProcessors(),
1219     defaultForkJoinWorkerThreadFactory);
1220     }
1221    
1222     /**
1223 dl 1.42 * Creates a {@code ForkJoinPool} with the indicated parallelism
1224     * level and using the {@linkplain
1225     * #defaultForkJoinWorkerThreadFactory default thread factory}.
1226 jsr166 1.17 *
1227 dl 1.42 * @param parallelism the parallelism level
1228 dl 1.1 * @throws IllegalArgumentException if parallelism less than or
1229 jsr166 1.47 * equal to zero, or greater than implementation limit
1230 dl 1.1 * @throws SecurityException if a security manager exists and
1231     * the caller is not permitted to modify threads
1232     * because it does not hold {@link
1233 jsr166 1.17 * java.lang.RuntimePermission}{@code ("modifyThread")}
1234 dl 1.1 */
1235     public ForkJoinPool(int parallelism) {
1236     this(parallelism, defaultForkJoinWorkerThreadFactory);
1237     }
1238    
1239     /**
1240 dl 1.42 * Creates a {@code ForkJoinPool} with parallelism equal to {@link
1241     * java.lang.Runtime#availableProcessors}, and using the given
1242     * thread factory.
1243 jsr166 1.17 *
1244 dl 1.1 * @param factory the factory for creating new threads
1245 jsr166 1.48 * @throws NullPointerException if the factory is null
1246 dl 1.1 * @throws SecurityException if a security manager exists and
1247     * the caller is not permitted to modify threads
1248     * because it does not hold {@link
1249 jsr166 1.17 * java.lang.RuntimePermission}{@code ("modifyThread")}
1250 dl 1.1 */
1251     public ForkJoinPool(ForkJoinWorkerThreadFactory factory) {
1252     this(Runtime.getRuntime().availableProcessors(), factory);
1253     }
1254    
1255     /**
1256 jsr166 1.41 * Creates a {@code ForkJoinPool} with the given parallelism and
1257     * thread factory.
1258 dl 1.1 *
1259 dl 1.42 * @param parallelism the parallelism level
1260 dl 1.1 * @param factory the factory for creating new threads
1261     * @throws IllegalArgumentException if parallelism less than or
1262 jsr166 1.47 * equal to zero, or greater than implementation limit
1263 jsr166 1.48 * @throws NullPointerException if the factory is null
1264 dl 1.1 * @throws SecurityException if a security manager exists and
1265     * the caller is not permitted to modify threads
1266     * because it does not hold {@link
1267 jsr166 1.17 * java.lang.RuntimePermission}{@code ("modifyThread")}
1268 dl 1.1 */
1269     public ForkJoinPool(int parallelism, ForkJoinWorkerThreadFactory factory) {
1270 dl 1.53 checkPermission();
1271     if (factory == null)
1272     throw new NullPointerException();
1273 dl 1.1 if (parallelism <= 0 || parallelism > MAX_THREADS)
1274     throw new IllegalArgumentException();
1275 dl 1.53 this.poolNumber = poolNumberGenerator.incrementAndGet();
1276     int arraySize = initialArraySizeFor(parallelism);
1277     this.parallelism = parallelism;
1278 dl 1.1 this.factory = factory;
1279     this.maxPoolSize = MAX_THREADS;
1280     this.maintainsParallelism = true;
1281 dl 1.53 this.workers = new ForkJoinWorkerThread[arraySize];
1282     this.submissionQueue = new LinkedTransferQueue<ForkJoinTask<?>>();
1283 dl 1.1 this.workerLock = new ReentrantLock();
1284 dl 1.53 this.terminationLatch = new CountDownLatch(1);
1285 dl 1.1 }
1286    
1287     /**
1288 dl 1.53 * Returns initial power of two size for workers array.
1289     * @param pc the initial parallelism level
1290     */
1291     private static int initialArraySizeFor(int pc) {
1292     // See Hackers Delight, sec 3.2. We know MAX_THREADS < (1 >>> 16)
1293     int size = pc < MAX_THREADS ? pc + 1 : MAX_THREADS;
1294     size |= size >>> 1;
1295     size |= size >>> 2;
1296     size |= size >>> 4;
1297     size |= size >>> 8;
1298     return size + 1;
1299 dl 1.1 }
1300    
1301     // Execution methods
1302    
1303     /**
1304     * Common code for execute, invoke and submit
1305     */
1306     private <T> void doSubmit(ForkJoinTask<T> task) {
1307 dl 1.23 if (task == null)
1308     throw new NullPointerException();
1309 dl 1.53 if (runState >= SHUTDOWN)
1310 dl 1.1 throw new RejectedExecutionException();
1311     submissionQueue.offer(task);
1312 dl 1.53 advanceEventCount();
1313     releaseWaiters();
1314 dl 1.56 ensureEnoughTotalWorkers();
1315 dl 1.1 }
1316    
1317     /**
1318 jsr166 1.17 * Performs the given task, returning its result upon completion.
1319     *
1320 dl 1.1 * @param task the task
1321     * @return the task's result
1322 jsr166 1.48 * @throws NullPointerException if the task is null
1323     * @throws RejectedExecutionException if the task cannot be
1324     * scheduled for execution
1325 dl 1.1 */
1326     public <T> T invoke(ForkJoinTask<T> task) {
1327     doSubmit(task);
1328     return task.join();
1329     }
1330    
1331     /**
1332     * Arranges for (asynchronous) execution of the given task.
1333 jsr166 1.17 *
1334 dl 1.1 * @param task the task
1335 jsr166 1.48 * @throws NullPointerException if the task is null
1336     * @throws RejectedExecutionException if the task cannot be
1337     * scheduled for execution
1338 dl 1.1 */
1339 dl 1.37 public void execute(ForkJoinTask<?> task) {
1340 dl 1.1 doSubmit(task);
1341     }
1342    
1343     // AbstractExecutorService methods
1344    
1345 jsr166 1.48 /**
1346     * @throws NullPointerException if the task is null
1347     * @throws RejectedExecutionException if the task cannot be
1348     * scheduled for execution
1349     */
1350 dl 1.1 public void execute(Runnable task) {
1351 dl 1.23 ForkJoinTask<?> job;
1352 jsr166 1.26 if (task instanceof ForkJoinTask<?>) // avoid re-wrap
1353     job = (ForkJoinTask<?>) task;
1354 dl 1.23 else
1355 dl 1.33 job = ForkJoinTask.adapt(task, null);
1356 dl 1.23 doSubmit(job);
1357 dl 1.1 }
1358    
1359 jsr166 1.48 /**
1360     * @throws NullPointerException if the task is null
1361     * @throws RejectedExecutionException if the task cannot be
1362     * scheduled for execution
1363     */
1364 dl 1.1 public <T> ForkJoinTask<T> submit(Callable<T> task) {
1365 dl 1.33 ForkJoinTask<T> job = ForkJoinTask.adapt(task);
1366 dl 1.1 doSubmit(job);
1367     return job;
1368     }
1369    
1370 jsr166 1.48 /**
1371     * @throws NullPointerException if the task is null
1372     * @throws RejectedExecutionException if the task cannot be
1373     * scheduled for execution
1374     */
1375 dl 1.1 public <T> ForkJoinTask<T> submit(Runnable task, T result) {
1376 dl 1.33 ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
1377 dl 1.1 doSubmit(job);
1378     return job;
1379     }
1380    
1381 jsr166 1.48 /**
1382     * @throws NullPointerException if the task is null
1383     * @throws RejectedExecutionException if the task cannot be
1384     * scheduled for execution
1385     */
1386 dl 1.1 public ForkJoinTask<?> submit(Runnable task) {
1387 dl 1.23 ForkJoinTask<?> job;
1388 jsr166 1.26 if (task instanceof ForkJoinTask<?>) // avoid re-wrap
1389     job = (ForkJoinTask<?>) task;
1390 dl 1.23 else
1391 dl 1.33 job = ForkJoinTask.adapt(task, null);
1392 dl 1.1 doSubmit(job);
1393     return job;
1394     }
1395    
1396     /**
1397 dl 1.23 * Submits a ForkJoinTask for execution.
1398     *
1399     * @param task the task to submit
1400     * @return the task
1401 jsr166 1.48 * @throws NullPointerException if the task is null
1402 dl 1.23 * @throws RejectedExecutionException if the task cannot be
1403     * scheduled for execution
1404     */
1405     public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
1406     doSubmit(task);
1407     return task;
1408     }
1409    
1410 jsr166 1.48 /**
1411     * @throws NullPointerException {@inheritDoc}
1412     * @throws RejectedExecutionException {@inheritDoc}
1413     */
1414 dl 1.1 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
1415 jsr166 1.20 ArrayList<ForkJoinTask<T>> forkJoinTasks =
1416 dl 1.1 new ArrayList<ForkJoinTask<T>>(tasks.size());
1417 jsr166 1.20 for (Callable<T> task : tasks)
1418 dl 1.33 forkJoinTasks.add(ForkJoinTask.adapt(task));
1419 jsr166 1.20 invoke(new InvokeAll<T>(forkJoinTasks));
1420    
1421     @SuppressWarnings({"unchecked", "rawtypes"})
1422 dl 1.54 List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
1423 jsr166 1.20 return futures;
1424 dl 1.1 }
1425    
1426     static final class InvokeAll<T> extends RecursiveAction {
1427     final ArrayList<ForkJoinTask<T>> tasks;
1428     InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
1429     public void compute() {
1430 jsr166 1.17 try { invokeAll(tasks); }
1431     catch (Exception ignore) {}
1432 dl 1.1 }
1433 jsr166 1.18 private static final long serialVersionUID = -7914297376763021607L;
1434 dl 1.1 }
1435    
1436     /**
1437 jsr166 1.17 * Returns the factory used for constructing new workers.
1438 dl 1.1 *
1439     * @return the factory used for constructing new workers
1440     */
1441     public ForkJoinWorkerThreadFactory getFactory() {
1442     return factory;
1443     }
1444    
1445     /**
1446 dl 1.2 * Returns the handler for internal worker threads that terminate
1447     * due to unrecoverable errors encountered while executing tasks.
1448 jsr166 1.17 *
1449 jsr166 1.28 * @return the handler, or {@code null} if none
1450 dl 1.2 */
1451     public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
1452 dl 1.53 workerCountReadFence();
1453     return ueh;
1454 dl 1.2 }
1455    
1456     /**
1457     * Sets the handler for internal worker threads that terminate due
1458     * to unrecoverable errors encountered while executing tasks.
1459     * Unless set, the current default or ThreadGroup handler is used
1460     * as handler.
1461     *
1462     * @param h the new handler
1463 jsr166 1.28 * @return the old handler, or {@code null} if none
1464 dl 1.2 * @throws SecurityException if a security manager exists and
1465     * the caller is not permitted to modify threads
1466     * because it does not hold {@link
1467 jsr166 1.17 * java.lang.RuntimePermission}{@code ("modifyThread")}
1468 dl 1.2 */
1469     public Thread.UncaughtExceptionHandler
1470     setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h) {
1471     checkPermission();
1472 dl 1.53 Thread.UncaughtExceptionHandler old = ueh;
1473     if (h != old) {
1474 dl 1.2 ueh = h;
1475 dl 1.56 ForkJoinWorkerThread[] ws = workers;
1476     int nws = ws.length;
1477     for (int i = 0; i < nws; ++i) {
1478     ForkJoinWorkerThread w = ws[i];
1479 dl 1.53 if (w != null)
1480     w.setUncaughtExceptionHandler(h);
1481 dl 1.2 }
1482     }
1483     return old;
1484     }
1485    
1486     /**
1487 jsr166 1.16 * Sets the target parallelism level of this pool.
1488 jsr166 1.17 *
1489 dl 1.1 * @param parallelism the target parallelism
1490     * @throws IllegalArgumentException if parallelism less than or
1491 jsr166 1.16 * equal to zero or greater than maximum size bounds
1492 dl 1.1 * @throws SecurityException if a security manager exists and
1493     * the caller is not permitted to modify threads
1494     * because it does not hold {@link
1495 jsr166 1.17 * java.lang.RuntimePermission}{@code ("modifyThread")}
1496 dl 1.1 */
1497     public void setParallelism(int parallelism) {
1498     checkPermission();
1499     if (parallelism <= 0 || parallelism > maxPoolSize)
1500     throw new IllegalArgumentException();
1501 dl 1.53 workerCountReadFence();
1502     int pc = this.parallelism;
1503     if (pc != parallelism) {
1504     this.parallelism = parallelism;
1505     workerCountWriteFence();
1506     // Release spares. If too many, some will die after re-suspend
1507 dl 1.56 ForkJoinWorkerThread[] ws = workers;
1508     int nws = ws.length;
1509     for (int i = 0; i < nws; ++i) {
1510     ForkJoinWorkerThread w = ws[i];
1511 dl 1.53 if (w != null && w.tryUnsuspend()) {
1512 dl 1.56 int c;
1513     do {} while (!UNSAFE.compareAndSwapInt
1514     (this, workerCountsOffset,
1515     c = workerCounts, c + ONE_RUNNING));
1516 dl 1.53 LockSupport.unpark(w);
1517 dl 1.50 }
1518 dl 1.1 }
1519 dl 1.53 ensureEnoughTotalWorkers();
1520     advanceEventCount();
1521     releaseWaiters(); // force config recheck by existing workers
1522 dl 1.1 }
1523     }
1524    
1525     /**
1526 dl 1.42 * Returns the targeted parallelism level of this pool.
1527 dl 1.1 *
1528 dl 1.42 * @return the targeted parallelism level of this pool
1529 dl 1.1 */
1530     public int getParallelism() {
1531 dl 1.53 // workerCountReadFence(); // inlined below
1532     int ignore = workerCounts;
1533 dl 1.1 return parallelism;
1534     }
1535    
1536     /**
1537     * Returns the number of worker threads that have started but not
1538     * yet terminated. This result returned by this method may differ
1539 jsr166 1.29 * from {@link #getParallelism} when threads are created to
1540 dl 1.1 * maintain parallelism when others are cooperatively blocked.
1541     *
1542     * @return the number of worker threads
1543     */
1544     public int getPoolSize() {
1545 dl 1.53 return workerCounts >>> TOTAL_COUNT_SHIFT;
1546 dl 1.1 }
1547    
1548     /**
1549     * Returns the maximum number of threads allowed to exist in the
1550 dl 1.45 * pool. Unless set using {@link #setMaximumPoolSize}, the
1551 dl 1.42 * maximum is an implementation-defined value designed only to
1552     * prevent runaway growth.
1553 jsr166 1.17 *
1554 dl 1.1 * @return the maximum
1555     */
1556     public int getMaximumPoolSize() {
1557 dl 1.53 workerCountReadFence();
1558 dl 1.1 return maxPoolSize;
1559     }
1560    
1561     /**
1562     * Sets the maximum number of threads allowed to exist in the
1563 dl 1.45 * pool. The given value should normally be greater than or equal
1564     * to the {@link #getParallelism parallelism} level. Setting this
1565     * value has no effect on current pool size. It controls
1566 dl 1.54 * construction of new threads. The use of this method may cause
1567     * tasks that intrinsically require extra threads for dependent
1568     * computations to indefinitely stall. If you are instead trying
1569 dl 1.55 * to minimize internal thread creation, consider setting {@link
1570 dl 1.54 * #setMaintainsParallelism} as false.
1571 jsr166 1.17 *
1572 jsr166 1.36 * @throws IllegalArgumentException if negative or greater than
1573 jsr166 1.16 * internal implementation limit
1574 dl 1.1 */
1575     public void setMaximumPoolSize(int newMax) {
1576     if (newMax < 0 || newMax > MAX_THREADS)
1577     throw new IllegalArgumentException();
1578     maxPoolSize = newMax;
1579 dl 1.53 workerCountWriteFence();
1580 dl 1.1 }
1581    
1582     /**
1583 jsr166 1.28 * Returns {@code true} if this pool dynamically maintains its
1584     * target parallelism level. If false, new threads are added only
1585     * to avoid possible starvation. This setting is by default true.
1586 jsr166 1.17 *
1587 jsr166 1.28 * @return {@code true} if maintains parallelism
1588 dl 1.1 */
1589     public boolean getMaintainsParallelism() {
1590 dl 1.53 workerCountReadFence();
1591 dl 1.1 return maintainsParallelism;
1592     }
1593    
1594     /**
1595     * Sets whether this pool dynamically maintains its target
1596     * parallelism level. If false, new threads are added only to
1597     * avoid possible starvation.
1598 jsr166 1.17 *
1599 jsr166 1.28 * @param enable {@code true} to maintain parallelism
1600 dl 1.1 */
1601     public void setMaintainsParallelism(boolean enable) {
1602     maintainsParallelism = enable;
1603 dl 1.53 workerCountWriteFence();
1604 dl 1.1 }
1605    
1606     /**
1607 dl 1.6 * Establishes local first-in-first-out scheduling mode for forked
1608     * tasks that are never joined. This mode may be more appropriate
1609     * than default locally stack-based mode in applications in which
1610     * worker threads only process asynchronous tasks. This method is
1611 jsr166 1.29 * designed to be invoked only when the pool is quiescent, and
1612 dl 1.6 * typically only before any tasks are submitted. The effects of
1613 jsr166 1.16 * invocations at other times may be unpredictable.
1614 dl 1.6 *
1615 jsr166 1.29 * @param async if {@code true}, use locally FIFO scheduling
1616 jsr166 1.16 * @return the previous mode
1617 jsr166 1.29 * @see #getAsyncMode
1618 dl 1.6 */
1619     public boolean setAsyncMode(boolean async) {
1620 dl 1.53 workerCountReadFence();
1621 dl 1.6 boolean oldMode = locallyFifo;
1622 dl 1.53 if (oldMode != async) {
1623     locallyFifo = async;
1624     workerCountWriteFence();
1625 dl 1.56 ForkJoinWorkerThread[] ws = workers;
1626     int nws = ws.length;
1627     for (int i = 0; i < nws; ++i) {
1628     ForkJoinWorkerThread w = ws[i];
1629 dl 1.53 if (w != null)
1630     w.setAsyncMode(async);
1631 dl 1.6 }
1632     }
1633     return oldMode;
1634     }
1635    
1636     /**
1637 jsr166 1.28 * Returns {@code true} if this pool uses local first-in-first-out
1638 jsr166 1.16 * scheduling mode for forked tasks that are never joined.
1639 dl 1.6 *
1640 jsr166 1.28 * @return {@code true} if this pool uses async mode
1641 jsr166 1.29 * @see #setAsyncMode
1642 dl 1.6 */
1643     public boolean getAsyncMode() {
1644 dl 1.53 workerCountReadFence();
1645 dl 1.6 return locallyFifo;
1646     }
1647    
1648     /**
1649 dl 1.2 * Returns an estimate of the number of worker threads that are
1650     * not blocked waiting to join tasks or for other managed
1651 dl 1.53 * synchronization. This method may overestimate the
1652     * number of running threads.
1653 dl 1.1 *
1654     * @return the number of worker threads
1655     */
1656     public int getRunningThreadCount() {
1657 dl 1.53 return workerCounts & RUNNING_COUNT_MASK;
1658 dl 1.1 }
1659    
1660     /**
1661 dl 1.2 * Returns an estimate of the number of threads that are currently
1662 dl 1.1 * stealing or executing tasks. This method may overestimate the
1663     * number of active threads.
1664 jsr166 1.17 *
1665 jsr166 1.16 * @return the number of active threads
1666 dl 1.1 */
1667     public int getActiveThreadCount() {
1668 dl 1.53 return runState & ACTIVE_COUNT_MASK;
1669 dl 1.1 }
1670    
1671     /**
1672 jsr166 1.28 * Returns {@code true} if all worker threads are currently idle.
1673     * An idle worker is one that cannot obtain a task to execute
1674     * because none are available to steal from other threads, and
1675     * there are no pending submissions to the pool. This method is
1676     * conservative; it might not return {@code true} immediately upon
1677     * idleness of all threads, but will eventually become true if
1678     * threads remain inactive.
1679 jsr166 1.17 *
1680 jsr166 1.28 * @return {@code true} if all threads are currently idle
1681 dl 1.1 */
1682     public boolean isQuiescent() {
1683 dl 1.53 return (runState & ACTIVE_COUNT_MASK) == 0;
1684 dl 1.1 }
1685    
1686     /**
1687     * Returns an estimate of the total number of tasks stolen from
1688     * one thread's work queue by another. The reported value
1689     * underestimates the actual total number of steals when the pool
1690     * is not quiescent. This value may be useful for monitoring and
1691 jsr166 1.17 * tuning fork/join programs: in general, steal counts should be
1692 dl 1.1 * high enough to keep threads busy, but low enough to avoid
1693     * overhead and contention across threads.
1694 jsr166 1.17 *
1695 jsr166 1.16 * @return the number of steals
1696 dl 1.1 */
1697     public long getStealCount() {
1698 dl 1.53 return stealCount;
1699 dl 1.1 }
1700    
1701     /**
1702 dl 1.2 * Returns an estimate of the total number of tasks currently held
1703     * in queues by worker threads (but not including tasks submitted
1704     * to the pool that have not begun executing). This value is only
1705     * an approximation, obtained by iterating across all threads in
1706     * the pool. This method may be useful for tuning task
1707     * granularities.
1708 jsr166 1.17 *
1709 jsr166 1.16 * @return the number of queued tasks
1710 dl 1.1 */
1711     public long getQueuedTaskCount() {
1712     long count = 0;
1713 dl 1.56 ForkJoinWorkerThread[] ws = workers;
1714     int nws = ws.length;
1715     for (int i = 0; i < nws; ++i) {
1716     ForkJoinWorkerThread w = ws[i];
1717 dl 1.53 if (w != null)
1718     count += w.getQueueSize();
1719 dl 1.1 }
1720     return count;
1721     }
1722    
1723     /**
1724 jsr166 1.40 * Returns an estimate of the number of tasks submitted to this
1725     * pool that have not yet begun executing. This method takes time
1726 dl 1.1 * proportional to the number of submissions.
1727 jsr166 1.17 *
1728 jsr166 1.16 * @return the number of queued submissions
1729 dl 1.1 */
1730     public int getQueuedSubmissionCount() {
1731     return submissionQueue.size();
1732     }
1733    
1734     /**
1735 jsr166 1.28 * Returns {@code true} if there are any tasks submitted to this
1736     * pool that have not yet begun executing.
1737 jsr166 1.17 *
1738 jsr166 1.16 * @return {@code true} if there are any queued submissions
1739 dl 1.1 */
1740     public boolean hasQueuedSubmissions() {
1741     return !submissionQueue.isEmpty();
1742     }
1743    
1744     /**
1745     * Removes and returns the next unexecuted submission if one is
1746     * available. This method may be useful in extensions to this
1747     * class that re-assign work in systems with multiple pools.
1748 jsr166 1.17 *
1749 jsr166 1.28 * @return the next submission, or {@code null} if none
1750 dl 1.1 */
1751     protected ForkJoinTask<?> pollSubmission() {
1752     return submissionQueue.poll();
1753     }
1754    
1755     /**
1756 dl 1.6 * Removes all available unexecuted submitted and forked tasks
1757     * from scheduling queues and adds them to the given collection,
1758     * without altering their execution status. These may include
1759 jsr166 1.41 * artificially generated or wrapped tasks. This method is
1760     * designed to be invoked only when the pool is known to be
1761 dl 1.6 * quiescent. Invocations at other times may not remove all
1762     * tasks. A failure encountered while attempting to add elements
1763 jsr166 1.16 * to collection {@code c} may result in elements being in
1764 dl 1.6 * neither, either or both collections when the associated
1765     * exception is thrown. The behavior of this operation is
1766     * undefined if the specified collection is modified while the
1767     * operation is in progress.
1768 jsr166 1.17 *
1769 dl 1.6 * @param c the collection to transfer elements into
1770     * @return the number of elements transferred
1771     */
1772 dl 1.30 protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
1773 dl 1.6 int n = submissionQueue.drainTo(c);
1774 dl 1.56 ForkJoinWorkerThread[] ws = workers;
1775     int nws = ws.length;
1776     for (int i = 0; i < nws; ++i) {
1777     ForkJoinWorkerThread w = ws[i];
1778 dl 1.53 if (w != null)
1779     n += w.drainTasksTo(c);
1780 dl 1.6 }
1781     return n;
1782     }
1783    
1784     /**
1785 dl 1.1 * Returns a string identifying this pool, as well as its state,
1786     * including indications of run state, parallelism level, and
1787     * worker and task counts.
1788     *
1789     * @return a string identifying this pool, as well as its state
1790     */
1791     public String toString() {
1792     long st = getStealCount();
1793     long qt = getQueuedTaskCount();
1794     long qs = getQueuedSubmissionCount();
1795 dl 1.53 int wc = workerCounts;
1796     int tc = wc >>> TOTAL_COUNT_SHIFT;
1797     int rc = wc & RUNNING_COUNT_MASK;
1798     int pc = parallelism;
1799     int rs = runState;
1800     int ac = rs & ACTIVE_COUNT_MASK;
1801 dl 1.1 return super.toString() +
1802 dl 1.53 "[" + runLevelToString(rs) +
1803     ", parallelism = " + pc +
1804     ", size = " + tc +
1805     ", active = " + ac +
1806     ", running = " + rc +
1807 dl 1.1 ", steals = " + st +
1808     ", tasks = " + qt +
1809     ", submissions = " + qs +
1810     "]";
1811     }
1812    
1813 dl 1.53 private static String runLevelToString(int s) {
1814     return ((s & TERMINATED) != 0 ? "Terminated" :
1815     ((s & TERMINATING) != 0 ? "Terminating" :
1816     ((s & SHUTDOWN) != 0 ? "Shutting down" :
1817     "Running")));
1818 dl 1.1 }
1819    
1820     /**
1821     * Initiates an orderly shutdown in which previously submitted
1822     * tasks are executed, but no new tasks will be accepted.
1823     * Invocation has no additional effect if already shut down.
1824     * Tasks that are in the process of being submitted concurrently
1825     * during the course of this method may or may not be rejected.
1826 jsr166 1.17 *
1827 dl 1.1 * @throws SecurityException if a security manager exists and
1828     * the caller is not permitted to modify threads
1829     * because it does not hold {@link
1830 jsr166 1.17 * java.lang.RuntimePermission}{@code ("modifyThread")}
1831 dl 1.1 */
1832     public void shutdown() {
1833     checkPermission();
1834 dl 1.53 advanceRunLevel(SHUTDOWN);
1835     tryTerminate(false);
1836 dl 1.1 }
1837    
1838     /**
1839 dl 1.42 * Attempts to cancel and/or stop all tasks, and reject all
1840     * subsequently submitted tasks. Tasks that are in the process of
1841     * being submitted or executed concurrently during the course of
1842     * this method may or may not be rejected. This method cancels
1843     * both existing and unexecuted tasks, in order to permit
1844     * termination in the presence of task dependencies. So the method
1845     * always returns an empty list (unlike the case for some other
1846     * Executors).
1847 jsr166 1.17 *
1848 dl 1.1 * @return an empty list
1849     * @throws SecurityException if a security manager exists and
1850     * the caller is not permitted to modify threads
1851     * because it does not hold {@link
1852 jsr166 1.17 * java.lang.RuntimePermission}{@code ("modifyThread")}
1853 dl 1.1 */
1854     public List<Runnable> shutdownNow() {
1855     checkPermission();
1856 dl 1.53 tryTerminate(true);
1857 dl 1.1 return Collections.emptyList();
1858     }
1859    
1860     /**
1861 jsr166 1.16 * Returns {@code true} if all tasks have completed following shut down.
1862 dl 1.1 *
1863 jsr166 1.16 * @return {@code true} if all tasks have completed following shut down
1864 dl 1.1 */
1865     public boolean isTerminated() {
1866 dl 1.53 return runState >= TERMINATED;
1867 dl 1.1 }
1868    
1869     /**
1870 jsr166 1.16 * Returns {@code true} if the process of termination has
1871 dl 1.42 * commenced but not yet completed. This method may be useful for
1872     * debugging. A return of {@code true} reported a sufficient
1873     * period after shutdown may indicate that submitted tasks have
1874     * ignored or suppressed interruption, causing this executor not
1875     * to properly terminate.
1876 dl 1.1 *
1877 dl 1.42 * @return {@code true} if terminating but not yet terminated
1878 dl 1.1 */
1879     public boolean isTerminating() {
1880 dl 1.53 return (runState & (TERMINATING|TERMINATED)) == TERMINATING;
1881 dl 1.1 }
1882    
1883     /**
1884 jsr166 1.16 * Returns {@code true} if this pool has been shut down.
1885 dl 1.1 *
1886 jsr166 1.16 * @return {@code true} if this pool has been shut down
1887 dl 1.1 */
1888     public boolean isShutdown() {
1889 dl 1.53 return runState >= SHUTDOWN;
1890 dl 1.42 }
1891    
1892     /**
1893 dl 1.1 * Blocks until all tasks have completed execution after a shutdown
1894     * request, or the timeout occurs, or the current thread is
1895     * interrupted, whichever happens first.
1896     *
1897     * @param timeout the maximum time to wait
1898     * @param unit the time unit of the timeout argument
1899 jsr166 1.16 * @return {@code true} if this executor terminated and
1900     * {@code false} if the timeout elapsed before termination
1901 dl 1.1 * @throws InterruptedException if interrupted while waiting
1902     */
1903     public boolean awaitTermination(long timeout, TimeUnit unit)
1904     throws InterruptedException {
1905 dl 1.53 return terminationLatch.await(timeout, unit);
1906 dl 1.1 }
1907    
1908     /**
1909     * Interface for extending managed parallelism for tasks running
1910 jsr166 1.35 * in {@link ForkJoinPool}s.
1911     *
1912     * <p>A {@code ManagedBlocker} provides two methods.
1913 jsr166 1.28 * Method {@code isReleasable} must return {@code true} if
1914     * blocking is not necessary. Method {@code block} blocks the
1915     * current thread if necessary (perhaps internally invoking
1916 jsr166 1.40 * {@code isReleasable} before actually blocking).
1917 jsr166 1.17 *
1918 dl 1.1 * <p>For example, here is a ManagedBlocker based on a
1919     * ReentrantLock:
1920 jsr166 1.17 * <pre> {@code
1921     * class ManagedLocker implements ManagedBlocker {
1922     * final ReentrantLock lock;
1923     * boolean hasLock = false;
1924     * ManagedLocker(ReentrantLock lock) { this.lock = lock; }
1925     * public boolean block() {
1926     * if (!hasLock)
1927     * lock.lock();
1928     * return true;
1929     * }
1930     * public boolean isReleasable() {
1931     * return hasLock || (hasLock = lock.tryLock());
1932 dl 1.1 * }
1933 jsr166 1.17 * }}</pre>
1934 dl 1.1 */
1935     public static interface ManagedBlocker {
1936     /**
1937     * Possibly blocks the current thread, for example waiting for
1938     * a lock or condition.
1939 jsr166 1.17 *
1940 jsr166 1.28 * @return {@code true} if no additional blocking is necessary
1941     * (i.e., if isReleasable would return true)
1942 dl 1.1 * @throws InterruptedException if interrupted while waiting
1943 jsr166 1.17 * (the method is not required to do so, but is allowed to)
1944 dl 1.1 */
1945     boolean block() throws InterruptedException;
1946    
1947     /**
1948 jsr166 1.28 * Returns {@code true} if blocking is unnecessary.
1949 dl 1.1 */
1950     boolean isReleasable();
1951     }
1952    
1953     /**
1954     * Blocks in accord with the given blocker. If the current thread
1955 jsr166 1.38 * is a {@link ForkJoinWorkerThread}, this method possibly
1956     * arranges for a spare thread to be activated if necessary to
1957     * ensure parallelism while the current thread is blocked.
1958 dl 1.1 *
1959 jsr166 1.38 * <p>If {@code maintainParallelism} is {@code true} and the pool
1960     * supports it ({@link #getMaintainsParallelism}), this method
1961     * attempts to maintain the pool's nominal parallelism. Otherwise
1962     * it activates a thread only if necessary to avoid complete
1963     * starvation. This option may be preferable when blockages use
1964     * timeouts, or are almost always brief.
1965     *
1966     * <p>If the caller is not a {@link ForkJoinTask}, this method is
1967     * behaviorally equivalent to
1968 jsr166 1.17 * <pre> {@code
1969     * while (!blocker.isReleasable())
1970     * if (blocker.block())
1971     * return;
1972     * }</pre>
1973 jsr166 1.38 *
1974     * If the caller is a {@code ForkJoinTask}, then the pool may
1975     * first be expanded to ensure parallelism, and later adjusted.
1976 dl 1.1 *
1977     * @param blocker the blocker
1978 jsr166 1.28 * @param maintainParallelism if {@code true} and supported by
1979     * this pool, attempt to maintain the pool's nominal parallelism;
1980     * otherwise activate a thread only if necessary to avoid
1981     * complete starvation.
1982 jsr166 1.16 * @throws InterruptedException if blocker.block did so
1983 dl 1.1 */
1984     public static void managedBlock(ManagedBlocker blocker,
1985     boolean maintainParallelism)
1986     throws InterruptedException {
1987     Thread t = Thread.currentThread();
1988 dl 1.53 if (t instanceof ForkJoinWorkerThread)
1989     ((ForkJoinWorkerThread) t).pool.
1990 dl 1.56 awaitBlocker(blocker, maintainParallelism);
1991 dl 1.53 else
1992     awaitBlocker(blocker);
1993 dl 1.1 }
1994    
1995 dl 1.53 /**
1996     * Performs Non-FJ blocking
1997     */
1998 dl 1.1 private static void awaitBlocker(ManagedBlocker blocker)
1999     throws InterruptedException {
2000 jsr166 1.17 do {} while (!blocker.isReleasable() && !blocker.block());
2001 dl 1.1 }
2002    
2003 dl 1.33 // AbstractExecutorService overrides. These rely on undocumented
2004     // fact that ForkJoinTask.adapt returns ForkJoinTasks that also
2005     // implement RunnableFuture.
2006 dl 1.2
2007     protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
2008 jsr166 1.34 return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
2009 dl 1.2 }
2010    
2011     protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
2012 jsr166 1.34 return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
2013 dl 1.2 }
2014    
2015 jsr166 1.27 // Unsafe mechanics
2016 dl 1.1
2017 jsr166 1.21 private static final sun.misc.Unsafe UNSAFE = getUnsafe();
2018 dl 1.53 private static final long workerCountsOffset =
2019     objectFieldOffset("workerCounts", ForkJoinPool.class);
2020     private static final long runStateOffset =
2021     objectFieldOffset("runState", ForkJoinPool.class);
2022 jsr166 1.25 private static final long eventCountOffset =
2023 jsr166 1.27 objectFieldOffset("eventCount", ForkJoinPool.class);
2024 dl 1.53 private static final long eventWaitersOffset =
2025     objectFieldOffset("eventWaiters",ForkJoinPool.class);
2026     private static final long stealCountOffset =
2027     objectFieldOffset("stealCount",ForkJoinPool.class);
2028    
2029 jsr166 1.27
2030     private static long objectFieldOffset(String field, Class<?> klazz) {
2031     try {
2032     return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
2033     } catch (NoSuchFieldException e) {
2034     // Convert Exception to corresponding Error
2035     NoSuchFieldError error = new NoSuchFieldError(field);
2036     error.initCause(e);
2037     throw error;
2038     }
2039     }
2040    
2041     /**
2042     * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
2043     * Replace with a simple call to Unsafe.getUnsafe when integrating
2044     * into a jdk.
2045     *
2046     * @return a sun.misc.Unsafe
2047     */
2048     private static sun.misc.Unsafe getUnsafe() {
2049     try {
2050     return sun.misc.Unsafe.getUnsafe();
2051     } catch (SecurityException se) {
2052     try {
2053     return java.security.AccessController.doPrivileged
2054     (new java.security
2055     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
2056     public sun.misc.Unsafe run() throws Exception {
2057     java.lang.reflect.Field f = sun.misc
2058     .Unsafe.class.getDeclaredField("theUnsafe");
2059     f.setAccessible(true);
2060     return (sun.misc.Unsafe) f.get(null);
2061     }});
2062     } catch (java.security.PrivilegedActionException e) {
2063     throw new RuntimeException("Could not initialize intrinsics",
2064     e.getCause());
2065     }
2066     }
2067     }
2068 dl 1.1 }