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

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