ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.14
Committed: Mon Apr 5 16:05:09 2010 UTC (14 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.13: +961 -989 lines
Log Message:
Sync with jsr166y versions

File Contents

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