ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.15
Committed: Sun Apr 18 12:54:57 2010 UTC (14 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.14: +64 -11 lines
Log Message:
Sync with jsr166y versions

File Contents

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