ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinPool.java
Revision: 1.57
Committed: Wed Jul 7 19:52:31 2010 UTC (13 years, 10 months ago) by dl
Branch: MAIN
Changes since 1.56: +302 -539 lines
Log Message:
Simplify APIs. See concurrency-interest postings for rationale

File Contents

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