ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.18
Committed: Wed Jul 7 20:41:24 2010 UTC (13 years, 10 months ago) by dl
Branch: MAIN
Changes since 1.17: +302 -538 lines
Log Message:
Sync with jsr166y changes

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