ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinPool.java
Revision: 1.33
Committed: Fri Jul 31 16:27:08 2009 UTC (14 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.32: +10 -61 lines
Log Message:
Refactor Adapted tasks into ForkJoinTask; mesh peek/pollNextLocalTask specs and code

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 jsr166y;
8
9 import java.util.concurrent.*;
10
11 import java.util.ArrayList;
12 import java.util.Arrays;
13 import java.util.Collection;
14 import java.util.Collections;
15 import java.util.List;
16 import java.util.concurrent.locks.Condition;
17 import java.util.concurrent.locks.LockSupport;
18 import java.util.concurrent.locks.ReentrantLock;
19 import java.util.concurrent.atomic.AtomicInteger;
20 import java.util.concurrent.atomic.AtomicLong;
21
22 /**
23 * An {@link ExecutorService} for running {@link ForkJoinTask}s.
24 * A ForkJoinPool provides the entry point for submissions from
25 * non-ForkJoinTasks, as well as management and monitoring operations.
26 * Normally a single ForkJoinPool is used for a large number of
27 * submitted tasks. Otherwise, use would not usually outweigh the
28 * construction and bookkeeping overhead of creating a large set of
29 * threads.
30 *
31 * <p>ForkJoinPools differ from other kinds of Executors mainly in
32 * that they provide <em>work-stealing</em>: all threads in the pool
33 * attempt to find and execute subtasks created by other active tasks
34 * (eventually blocking if none exist). This makes them efficient when
35 * most tasks spawn other subtasks (as do most ForkJoinTasks), as well
36 * as the mixed execution of some plain Runnable- or Callable- based
37 * activities along with ForkJoinTasks. When setting {@linkplain
38 * #setAsyncMode async mode}, a ForkJoinPool may also be appropriate
39 * for use with fine-grained tasks that are never joined. Otherwise,
40 * other ExecutorService implementations are typically more
41 * appropriate choices.
42 *
43 * <p>A ForkJoinPool may be constructed with a given parallelism level
44 * (target pool size), which it attempts to maintain by dynamically
45 * adding, suspending, or resuming threads, even if some tasks are
46 * waiting to join others. However, no such adjustments are performed
47 * in the face of blocked IO or other unmanaged synchronization. The
48 * nested {@link ManagedBlocker} interface enables extension of
49 * the kinds of synchronization accommodated. The target parallelism
50 * level may also be changed dynamically ({@link #setParallelism})
51 * and thread construction can be limited using methods
52 * {@link #setMaximumPoolSize} and/or
53 * {@link #setMaintainsParallelism}.
54 *
55 * <p>In addition to execution and lifecycle control methods, this
56 * class provides status check methods (for example
57 * {@link #getStealCount}) that are intended to aid in developing,
58 * tuning, and monitoring fork/join applications. Also, method
59 * {@link #toString} returns indications of pool state in a
60 * convenient form for informal monitoring.
61 *
62 * <p><b>Implementation notes</b>: This implementation restricts the
63 * maximum number of running threads to 32767. Attempts to create
64 * pools with greater than the maximum result in
65 * IllegalArgumentExceptions.
66 *
67 * @since 1.7
68 * @author Doug Lea
69 */
70 public class ForkJoinPool extends AbstractExecutorService {
71
72 /*
73 * See the extended comments interspersed below for design,
74 * rationale, and walkthroughs.
75 */
76
77 /** Mask for packing and unpacking shorts */
78 private static final int shortMask = 0xffff;
79
80 /** Max pool size -- must be a power of two minus 1 */
81 private static final int MAX_THREADS = 0x7FFF;
82
83 /**
84 * Factory for creating new ForkJoinWorkerThreads. A
85 * ForkJoinWorkerThreadFactory must be defined and used for
86 * ForkJoinWorkerThread subclasses that extend base functionality
87 * or initialize threads with different contexts.
88 */
89 public static interface ForkJoinWorkerThreadFactory {
90 /**
91 * Returns a new worker thread operating in the given pool.
92 *
93 * @param pool the pool this thread works in
94 * @throws NullPointerException if pool is null
95 */
96 public ForkJoinWorkerThread newThread(ForkJoinPool pool);
97 }
98
99 /**
100 * Default ForkJoinWorkerThreadFactory implementation; creates a
101 * new ForkJoinWorkerThread.
102 */
103 static class DefaultForkJoinWorkerThreadFactory
104 implements ForkJoinWorkerThreadFactory {
105 public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
106 try {
107 return new ForkJoinWorkerThread(pool);
108 } catch (OutOfMemoryError oom) {
109 return null;
110 }
111 }
112 }
113
114 /**
115 * Creates a new ForkJoinWorkerThread. This factory is used unless
116 * overridden in ForkJoinPool constructors.
117 */
118 public static final ForkJoinWorkerThreadFactory
119 defaultForkJoinWorkerThreadFactory =
120 new DefaultForkJoinWorkerThreadFactory();
121
122 /**
123 * Permission required for callers of methods that may start or
124 * kill threads.
125 */
126 private static final RuntimePermission modifyThreadPermission =
127 new RuntimePermission("modifyThread");
128
129 /**
130 * If there is a security manager, makes sure caller has
131 * permission to modify threads.
132 */
133 private static void checkPermission() {
134 SecurityManager security = System.getSecurityManager();
135 if (security != null)
136 security.checkPermission(modifyThreadPermission);
137 }
138
139 /**
140 * Generator for assigning sequence numbers as pool names.
141 */
142 private static final AtomicInteger poolNumberGenerator =
143 new AtomicInteger();
144
145 /**
146 * Array holding all worker threads in the pool. Initialized upon
147 * first use. Array size must be a power of two. Updates and
148 * replacements are protected by workerLock, but it is always kept
149 * in a consistent enough state to be randomly accessed without
150 * locking by workers performing work-stealing.
151 */
152 volatile ForkJoinWorkerThread[] workers;
153
154 /**
155 * Lock protecting access to workers.
156 */
157 private final ReentrantLock workerLock;
158
159 /**
160 * Condition for awaitTermination.
161 */
162 private final Condition termination;
163
164 /**
165 * The uncaught exception handler used when any worker
166 * abruptly terminates
167 */
168 private Thread.UncaughtExceptionHandler ueh;
169
170 /**
171 * Creation factory for worker threads.
172 */
173 private final ForkJoinWorkerThreadFactory factory;
174
175 /**
176 * Head of stack of threads that were created to maintain
177 * parallelism when other threads blocked, but have since
178 * suspended when the parallelism level rose.
179 */
180 private volatile WaitQueueNode spareStack;
181
182 /**
183 * Sum of per-thread steal counts, updated only when threads are
184 * idle or terminating.
185 */
186 private final AtomicLong stealCount;
187
188 /**
189 * Queue for external submissions.
190 */
191 private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue;
192
193 /**
194 * Head of Treiber stack for barrier sync. See below for explanation.
195 */
196 private volatile WaitQueueNode syncStack;
197
198 /**
199 * The count for event barrier
200 */
201 private volatile long eventCount;
202
203 /**
204 * Pool number, just for assigning useful names to worker threads
205 */
206 private final int poolNumber;
207
208 /**
209 * The maximum allowed pool size
210 */
211 private volatile int maxPoolSize;
212
213 /**
214 * The desired parallelism level, updated only under workerLock.
215 */
216 private volatile int parallelism;
217
218 /**
219 * True if use local fifo, not default lifo, for local polling
220 */
221 private volatile boolean locallyFifo;
222
223 /**
224 * Holds number of total (i.e., created and not yet terminated)
225 * and running (i.e., not blocked on joins or other managed sync)
226 * threads, packed into one int to ensure consistent snapshot when
227 * making decisions about creating and suspending spare
228 * threads. Updated only by CAS. Note: CASes in
229 * updateRunningCount and preJoin assume that running active count
230 * is in low word, so need to be modified if this changes.
231 */
232 private volatile int workerCounts;
233
234 private static int totalCountOf(int s) { return s >>> 16; }
235 private static int runningCountOf(int s) { return s & shortMask; }
236 private static int workerCountsFor(int t, int r) { return (t << 16) + r; }
237
238 /**
239 * Adds delta (which may be negative) to running count. This must
240 * be called before (with negative arg) and after (with positive)
241 * any managed synchronization (i.e., mainly, joins).
242 *
243 * @param delta the number to add
244 */
245 final void updateRunningCount(int delta) {
246 int s;
247 do {} while (!casWorkerCounts(s = workerCounts, s + delta));
248 }
249
250 /**
251 * Adds delta (which may be negative) to both total and running
252 * count. This must be called upon creation and termination of
253 * worker threads.
254 *
255 * @param delta the number to add
256 */
257 private void updateWorkerCount(int delta) {
258 int d = delta + (delta << 16); // add to both lo and hi parts
259 int s;
260 do {} while (!casWorkerCounts(s = workerCounts, s + d));
261 }
262
263 /**
264 * Lifecycle control. High word contains runState, low word
265 * contains the number of workers that are (probably) executing
266 * tasks. This value is atomically incremented before a worker
267 * gets a task to run, and decremented when worker has no tasks
268 * and cannot find any. These two fields are bundled together to
269 * support correct termination triggering. Note: activeCount
270 * CAS'es cheat by assuming active count is in low word, so need
271 * to be modified if this changes
272 */
273 private volatile int runControl;
274
275 // RunState values. Order among values matters
276 private static final int RUNNING = 0;
277 private static final int SHUTDOWN = 1;
278 private static final int TERMINATING = 2;
279 private static final int TERMINATED = 3;
280
281 private static int runStateOf(int c) { return c >>> 16; }
282 private static int activeCountOf(int c) { return c & shortMask; }
283 private static int runControlFor(int r, int a) { return (r << 16) + a; }
284
285 /**
286 * Tries incrementing active count; fails on contention.
287 * Called by workers before/during executing tasks.
288 *
289 * @return true on success
290 */
291 final boolean tryIncrementActiveCount() {
292 int c = runControl;
293 return casRunControl(c, c+1);
294 }
295
296 /**
297 * Tries decrementing active count; fails on contention.
298 * Possibly triggers termination on success.
299 * Called by workers when they can't find tasks.
300 *
301 * @return true on success
302 */
303 final boolean tryDecrementActiveCount() {
304 int c = runControl;
305 int nextc = c - 1;
306 if (!casRunControl(c, nextc))
307 return false;
308 if (canTerminateOnShutdown(nextc))
309 terminateOnShutdown();
310 return true;
311 }
312
313 /**
314 * Returns {@code true} if argument represents zero active count
315 * and nonzero runstate, which is the triggering condition for
316 * terminating on shutdown.
317 */
318 private static boolean canTerminateOnShutdown(int c) {
319 // i.e. least bit is nonzero runState bit
320 return ((c & -c) >>> 16) != 0;
321 }
322
323 /**
324 * Transition run state to at least the given state. Return true
325 * if not already at least given state.
326 */
327 private boolean transitionRunStateTo(int state) {
328 for (;;) {
329 int c = runControl;
330 if (runStateOf(c) >= state)
331 return false;
332 if (casRunControl(c, runControlFor(state, activeCountOf(c))))
333 return true;
334 }
335 }
336
337 /**
338 * Controls whether to add spares to maintain parallelism
339 */
340 private volatile boolean maintainsParallelism;
341
342 // Constructors
343
344 /**
345 * Creates a ForkJoinPool with a pool size equal to the number of
346 * processors available on the system, using the default
347 * ForkJoinWorkerThreadFactory.
348 *
349 * @throws SecurityException if a security manager exists and
350 * the caller is not permitted to modify threads
351 * because it does not hold {@link
352 * java.lang.RuntimePermission}{@code ("modifyThread")}
353 */
354 public ForkJoinPool() {
355 this(Runtime.getRuntime().availableProcessors(),
356 defaultForkJoinWorkerThreadFactory);
357 }
358
359 /**
360 * Creates a ForkJoinPool with the indicated parallelism level
361 * threads and using the default ForkJoinWorkerThreadFactory.
362 *
363 * @param parallelism the number of worker threads
364 * @throws IllegalArgumentException if parallelism less than or
365 * equal to zero
366 * @throws SecurityException if a security manager exists and
367 * the caller is not permitted to modify threads
368 * because it does not hold {@link
369 * java.lang.RuntimePermission}{@code ("modifyThread")}
370 */
371 public ForkJoinPool(int parallelism) {
372 this(parallelism, defaultForkJoinWorkerThreadFactory);
373 }
374
375 /**
376 * Creates a ForkJoinPool with parallelism equal to the number of
377 * processors available on the system and using the given
378 * ForkJoinWorkerThreadFactory.
379 *
380 * @param factory the factory for creating new threads
381 * @throws NullPointerException if factory is null
382 * @throws SecurityException if a security manager exists and
383 * the caller is not permitted to modify threads
384 * because it does not hold {@link
385 * java.lang.RuntimePermission}{@code ("modifyThread")}
386 */
387 public ForkJoinPool(ForkJoinWorkerThreadFactory factory) {
388 this(Runtime.getRuntime().availableProcessors(), factory);
389 }
390
391 /**
392 * Creates a ForkJoinPool with the given parallelism and factory.
393 *
394 * @param parallelism the targeted number of worker threads
395 * @param factory the factory for creating new threads
396 * @throws IllegalArgumentException if parallelism less than or
397 * equal to zero, or greater than implementation limit
398 * @throws NullPointerException if factory is null
399 * @throws SecurityException if a security manager exists and
400 * the caller is not permitted to modify threads
401 * because it does not hold {@link
402 * java.lang.RuntimePermission}{@code ("modifyThread")}
403 */
404 public ForkJoinPool(int parallelism, ForkJoinWorkerThreadFactory factory) {
405 if (parallelism <= 0 || parallelism > MAX_THREADS)
406 throw new IllegalArgumentException();
407 if (factory == null)
408 throw new NullPointerException();
409 checkPermission();
410 this.factory = factory;
411 this.parallelism = parallelism;
412 this.maxPoolSize = MAX_THREADS;
413 this.maintainsParallelism = true;
414 this.poolNumber = poolNumberGenerator.incrementAndGet();
415 this.workerLock = new ReentrantLock();
416 this.termination = workerLock.newCondition();
417 this.stealCount = new AtomicLong();
418 this.submissionQueue = new LinkedTransferQueue<ForkJoinTask<?>>();
419 // worker array and workers are lazily constructed
420 }
421
422 /**
423 * Creates a new worker thread using factory.
424 *
425 * @param index the index to assign worker
426 * @return new worker, or null of factory failed
427 */
428 private ForkJoinWorkerThread createWorker(int index) {
429 Thread.UncaughtExceptionHandler h = ueh;
430 ForkJoinWorkerThread w = factory.newThread(this);
431 if (w != null) {
432 w.poolIndex = index;
433 w.setDaemon(true);
434 w.setAsyncMode(locallyFifo);
435 w.setName("ForkJoinPool-" + poolNumber + "-worker-" + index);
436 if (h != null)
437 w.setUncaughtExceptionHandler(h);
438 }
439 return w;
440 }
441
442 /**
443 * Returns a good size for worker array given pool size.
444 * Currently requires size to be a power of two.
445 */
446 private static int arraySizeFor(int poolSize) {
447 return (poolSize <= 1) ? 1 :
448 (1 << (32 - Integer.numberOfLeadingZeros(poolSize-1)));
449 }
450
451 /**
452 * Creates or resizes array if necessary to hold newLength.
453 * Call only under exclusion.
454 *
455 * @return the array
456 */
457 private ForkJoinWorkerThread[] ensureWorkerArrayCapacity(int newLength) {
458 ForkJoinWorkerThread[] ws = workers;
459 if (ws == null)
460 return workers = new ForkJoinWorkerThread[arraySizeFor(newLength)];
461 else if (newLength > ws.length)
462 return workers = Arrays.copyOf(ws, arraySizeFor(newLength));
463 else
464 return ws;
465 }
466
467 /**
468 * Tries to shrink workers into smaller array after one or more terminate.
469 */
470 private void tryShrinkWorkerArray() {
471 ForkJoinWorkerThread[] ws = workers;
472 if (ws != null) {
473 int len = ws.length;
474 int last = len - 1;
475 while (last >= 0 && ws[last] == null)
476 --last;
477 int newLength = arraySizeFor(last+1);
478 if (newLength < len)
479 workers = Arrays.copyOf(ws, newLength);
480 }
481 }
482
483 /**
484 * Initializes workers if necessary.
485 */
486 final void ensureWorkerInitialization() {
487 ForkJoinWorkerThread[] ws = workers;
488 if (ws == null) {
489 final ReentrantLock lock = this.workerLock;
490 lock.lock();
491 try {
492 ws = workers;
493 if (ws == null) {
494 int ps = parallelism;
495 ws = ensureWorkerArrayCapacity(ps);
496 for (int i = 0; i < ps; ++i) {
497 ForkJoinWorkerThread w = createWorker(i);
498 if (w != null) {
499 ws[i] = w;
500 w.start();
501 updateWorkerCount(1);
502 }
503 }
504 }
505 } finally {
506 lock.unlock();
507 }
508 }
509 }
510
511 /**
512 * Worker creation and startup for threads added via setParallelism.
513 */
514 private void createAndStartAddedWorkers() {
515 resumeAllSpares(); // Allow spares to convert to nonspare
516 int ps = parallelism;
517 ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(ps);
518 int len = ws.length;
519 // Sweep through slots, to keep lowest indices most populated
520 int k = 0;
521 while (k < len) {
522 if (ws[k] != null) {
523 ++k;
524 continue;
525 }
526 int s = workerCounts;
527 int tc = totalCountOf(s);
528 int rc = runningCountOf(s);
529 if (rc >= ps || tc >= ps)
530 break;
531 if (casWorkerCounts (s, workerCountsFor(tc+1, rc+1))) {
532 ForkJoinWorkerThread w = createWorker(k);
533 if (w != null) {
534 ws[k++] = w;
535 w.start();
536 }
537 else {
538 updateWorkerCount(-1); // back out on failed creation
539 break;
540 }
541 }
542 }
543 }
544
545 // Execution methods
546
547 /**
548 * Common code for execute, invoke and submit
549 */
550 private <T> void doSubmit(ForkJoinTask<T> task) {
551 if (task == null)
552 throw new NullPointerException();
553 if (isShutdown())
554 throw new RejectedExecutionException();
555 if (workers == null)
556 ensureWorkerInitialization();
557 submissionQueue.offer(task);
558 signalIdleWorkers();
559 }
560
561 /**
562 * Performs the given task, returning its result upon completion.
563 *
564 * @param task the task
565 * @return the task's result
566 * @throws NullPointerException if task is null
567 * @throws RejectedExecutionException if pool is shut down
568 */
569 public <T> T invoke(ForkJoinTask<T> task) {
570 doSubmit(task);
571 return task.join();
572 }
573
574 /**
575 * Arranges for (asynchronous) execution of the given task.
576 *
577 * @param task the task
578 * @throws NullPointerException if task is null
579 * @throws RejectedExecutionException if pool is shut down
580 */
581 public <T> void execute(ForkJoinTask<T> task) {
582 doSubmit(task);
583 }
584
585 // AbstractExecutorService methods
586
587 public void execute(Runnable task) {
588 ForkJoinTask<?> job;
589 if (task instanceof ForkJoinTask<?>) // avoid re-wrap
590 job = (ForkJoinTask<?>) task;
591 else
592 job = ForkJoinTask.adapt(task, null);
593 doSubmit(job);
594 }
595
596 public <T> ForkJoinTask<T> submit(Callable<T> task) {
597 ForkJoinTask<T> job = ForkJoinTask.adapt(task);
598 doSubmit(job);
599 return job;
600 }
601
602 public <T> ForkJoinTask<T> submit(Runnable task, T result) {
603 ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
604 doSubmit(job);
605 return job;
606 }
607
608 public ForkJoinTask<?> submit(Runnable task) {
609 ForkJoinTask<?> job;
610 if (task instanceof ForkJoinTask<?>) // avoid re-wrap
611 job = (ForkJoinTask<?>) task;
612 else
613 job = ForkJoinTask.adapt(task, null);
614 doSubmit(job);
615 return job;
616 }
617
618 /**
619 * Submits a ForkJoinTask for execution.
620 *
621 * @param task the task to submit
622 * @return the task
623 * @throws RejectedExecutionException if the task cannot be
624 * scheduled for execution
625 * @throws NullPointerException if the task is null
626 */
627 public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
628 doSubmit(task);
629 return task;
630 }
631
632
633 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
634 ArrayList<ForkJoinTask<T>> forkJoinTasks =
635 new ArrayList<ForkJoinTask<T>>(tasks.size());
636 for (Callable<T> task : tasks)
637 forkJoinTasks.add(ForkJoinTask.adapt(task));
638 invoke(new InvokeAll<T>(forkJoinTasks));
639
640 @SuppressWarnings({"unchecked", "rawtypes"})
641 List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
642 return futures;
643 }
644
645 static final class InvokeAll<T> extends RecursiveAction {
646 final ArrayList<ForkJoinTask<T>> tasks;
647 InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
648 public void compute() {
649 try { invokeAll(tasks); }
650 catch (Exception ignore) {}
651 }
652 private static final long serialVersionUID = -7914297376763021607L;
653 }
654
655 // Configuration and status settings and queries
656
657 /**
658 * Returns the factory used for constructing new workers.
659 *
660 * @return the factory used for constructing new workers
661 */
662 public ForkJoinWorkerThreadFactory getFactory() {
663 return factory;
664 }
665
666 /**
667 * Returns the handler for internal worker threads that terminate
668 * due to unrecoverable errors encountered while executing tasks.
669 *
670 * @return the handler, or {@code null} if none
671 */
672 public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
673 Thread.UncaughtExceptionHandler h;
674 final ReentrantLock lock = this.workerLock;
675 lock.lock();
676 try {
677 h = ueh;
678 } finally {
679 lock.unlock();
680 }
681 return h;
682 }
683
684 /**
685 * Sets the handler for internal worker threads that terminate due
686 * to unrecoverable errors encountered while executing tasks.
687 * Unless set, the current default or ThreadGroup handler is used
688 * as handler.
689 *
690 * @param h the new handler
691 * @return the old handler, or {@code null} if none
692 * @throws SecurityException if a security manager exists and
693 * the caller is not permitted to modify threads
694 * because it does not hold {@link
695 * java.lang.RuntimePermission}{@code ("modifyThread")}
696 */
697 public Thread.UncaughtExceptionHandler
698 setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h) {
699 checkPermission();
700 Thread.UncaughtExceptionHandler old = null;
701 final ReentrantLock lock = this.workerLock;
702 lock.lock();
703 try {
704 old = ueh;
705 ueh = h;
706 ForkJoinWorkerThread[] ws = workers;
707 if (ws != null) {
708 for (int i = 0; i < ws.length; ++i) {
709 ForkJoinWorkerThread w = ws[i];
710 if (w != null)
711 w.setUncaughtExceptionHandler(h);
712 }
713 }
714 } finally {
715 lock.unlock();
716 }
717 return old;
718 }
719
720
721 /**
722 * Sets the target parallelism level of this pool.
723 *
724 * @param parallelism the target parallelism
725 * @throws IllegalArgumentException if parallelism less than or
726 * equal to zero or greater than maximum size bounds
727 * @throws SecurityException if a security manager exists and
728 * the caller is not permitted to modify threads
729 * because it does not hold {@link
730 * java.lang.RuntimePermission}{@code ("modifyThread")}
731 */
732 public void setParallelism(int parallelism) {
733 checkPermission();
734 if (parallelism <= 0 || parallelism > maxPoolSize)
735 throw new IllegalArgumentException();
736 final ReentrantLock lock = this.workerLock;
737 lock.lock();
738 try {
739 if (!isTerminating()) {
740 int p = this.parallelism;
741 this.parallelism = parallelism;
742 if (parallelism > p)
743 createAndStartAddedWorkers();
744 else
745 trimSpares();
746 }
747 } finally {
748 lock.unlock();
749 }
750 signalIdleWorkers();
751 }
752
753 /**
754 * Returns the targeted number of worker threads in this pool.
755 *
756 * @return the targeted number of worker threads in this pool
757 */
758 public int getParallelism() {
759 return parallelism;
760 }
761
762 /**
763 * Returns the number of worker threads that have started but not
764 * yet terminated. This result returned by this method may differ
765 * from {@link #getParallelism} when threads are created to
766 * maintain parallelism when others are cooperatively blocked.
767 *
768 * @return the number of worker threads
769 */
770 public int getPoolSize() {
771 return totalCountOf(workerCounts);
772 }
773
774 /**
775 * Returns the maximum number of threads allowed to exist in the
776 * pool, even if there are insufficient unblocked running threads.
777 *
778 * @return the maximum
779 */
780 public int getMaximumPoolSize() {
781 return maxPoolSize;
782 }
783
784 /**
785 * Sets the maximum number of threads allowed to exist in the
786 * pool, even if there are insufficient unblocked running threads.
787 * Setting this value has no effect on current pool size. It
788 * controls construction of new threads.
789 *
790 * @throws IllegalArgumentException if negative or greater then
791 * internal implementation limit
792 */
793 public void setMaximumPoolSize(int newMax) {
794 if (newMax < 0 || newMax > MAX_THREADS)
795 throw new IllegalArgumentException();
796 maxPoolSize = newMax;
797 }
798
799
800 /**
801 * Returns {@code true} if this pool dynamically maintains its
802 * target parallelism level. If false, new threads are added only
803 * to avoid possible starvation. This setting is by default true.
804 *
805 * @return {@code true} if maintains parallelism
806 */
807 public boolean getMaintainsParallelism() {
808 return maintainsParallelism;
809 }
810
811 /**
812 * Sets whether this pool dynamically maintains its target
813 * parallelism level. If false, new threads are added only to
814 * avoid possible starvation.
815 *
816 * @param enable {@code true} to maintain parallelism
817 */
818 public void setMaintainsParallelism(boolean enable) {
819 maintainsParallelism = enable;
820 }
821
822 /**
823 * Establishes local first-in-first-out scheduling mode for forked
824 * tasks that are never joined. This mode may be more appropriate
825 * than default locally stack-based mode in applications in which
826 * worker threads only process asynchronous tasks. This method is
827 * designed to be invoked only when the pool is quiescent, and
828 * typically only before any tasks are submitted. The effects of
829 * invocations at other times may be unpredictable.
830 *
831 * @param async if {@code true}, use locally FIFO scheduling
832 * @return the previous mode
833 * @see #getAsyncMode
834 */
835 public boolean setAsyncMode(boolean async) {
836 boolean oldMode = locallyFifo;
837 locallyFifo = async;
838 ForkJoinWorkerThread[] ws = workers;
839 if (ws != null) {
840 for (int i = 0; i < ws.length; ++i) {
841 ForkJoinWorkerThread t = ws[i];
842 if (t != null)
843 t.setAsyncMode(async);
844 }
845 }
846 return oldMode;
847 }
848
849 /**
850 * Returns {@code true} if this pool uses local first-in-first-out
851 * scheduling mode for forked tasks that are never joined.
852 *
853 * @return {@code true} if this pool uses async mode
854 * @see #setAsyncMode
855 */
856 public boolean getAsyncMode() {
857 return locallyFifo;
858 }
859
860 /**
861 * Returns an estimate of the number of worker threads that are
862 * not blocked waiting to join tasks or for other managed
863 * synchronization.
864 *
865 * @return the number of worker threads
866 */
867 public int getRunningThreadCount() {
868 return runningCountOf(workerCounts);
869 }
870
871 /**
872 * Returns an estimate of the number of threads that are currently
873 * stealing or executing tasks. This method may overestimate the
874 * number of active threads.
875 *
876 * @return the number of active threads
877 */
878 public int getActiveThreadCount() {
879 return activeCountOf(runControl);
880 }
881
882 /**
883 * Returns an estimate of the number of threads that are currently
884 * idle waiting for tasks. This method may underestimate the
885 * number of idle threads.
886 *
887 * @return the number of idle threads
888 */
889 final int getIdleThreadCount() {
890 int c = runningCountOf(workerCounts) - activeCountOf(runControl);
891 return (c <= 0) ? 0 : c;
892 }
893
894 /**
895 * Returns {@code true} if all worker threads are currently idle.
896 * An idle worker is one that cannot obtain a task to execute
897 * because none are available to steal from other threads, and
898 * there are no pending submissions to the pool. This method is
899 * conservative; it might not return {@code true} immediately upon
900 * idleness of all threads, but will eventually become true if
901 * threads remain inactive.
902 *
903 * @return {@code true} if all threads are currently idle
904 */
905 public boolean isQuiescent() {
906 return activeCountOf(runControl) == 0;
907 }
908
909 /**
910 * Returns an estimate of the total number of tasks stolen from
911 * one thread's work queue by another. The reported value
912 * underestimates the actual total number of steals when the pool
913 * is not quiescent. This value may be useful for monitoring and
914 * tuning fork/join programs: in general, steal counts should be
915 * high enough to keep threads busy, but low enough to avoid
916 * overhead and contention across threads.
917 *
918 * @return the number of steals
919 */
920 public long getStealCount() {
921 return stealCount.get();
922 }
923
924 /**
925 * Accumulates steal count from a worker.
926 * Call only when worker known to be idle.
927 */
928 private void updateStealCount(ForkJoinWorkerThread w) {
929 int sc = w.getAndClearStealCount();
930 if (sc != 0)
931 stealCount.addAndGet(sc);
932 }
933
934 /**
935 * Returns an estimate of the total number of tasks currently held
936 * in queues by worker threads (but not including tasks submitted
937 * to the pool that have not begun executing). This value is only
938 * an approximation, obtained by iterating across all threads in
939 * the pool. This method may be useful for tuning task
940 * granularities.
941 *
942 * @return the number of queued tasks
943 */
944 public long getQueuedTaskCount() {
945 long count = 0;
946 ForkJoinWorkerThread[] ws = workers;
947 if (ws != null) {
948 for (int i = 0; i < ws.length; ++i) {
949 ForkJoinWorkerThread t = ws[i];
950 if (t != null)
951 count += t.getQueueSize();
952 }
953 }
954 return count;
955 }
956
957 /**
958 * Returns an estimate of the number tasks submitted to this pool
959 * that have not yet begun executing. This method takes time
960 * proportional to the number of submissions.
961 *
962 * @return the number of queued submissions
963 */
964 public int getQueuedSubmissionCount() {
965 return submissionQueue.size();
966 }
967
968 /**
969 * Returns {@code true} if there are any tasks submitted to this
970 * pool that have not yet begun executing.
971 *
972 * @return {@code true} if there are any queued submissions
973 */
974 public boolean hasQueuedSubmissions() {
975 return !submissionQueue.isEmpty();
976 }
977
978 /**
979 * Removes and returns the next unexecuted submission if one is
980 * available. This method may be useful in extensions to this
981 * class that re-assign work in systems with multiple pools.
982 *
983 * @return the next submission, or {@code null} if none
984 */
985 protected ForkJoinTask<?> pollSubmission() {
986 return submissionQueue.poll();
987 }
988
989 /**
990 * Removes all available unexecuted submitted and forked tasks
991 * from scheduling queues and adds them to the given collection,
992 * without altering their execution status. These may include
993 * artificially generated or wrapped tasks. This method is designed
994 * to be invoked only when the pool is known to be
995 * quiescent. Invocations at other times may not remove all
996 * tasks. A failure encountered while attempting to add elements
997 * to collection {@code c} may result in elements being in
998 * neither, either or both collections when the associated
999 * exception is thrown. The behavior of this operation is
1000 * undefined if the specified collection is modified while the
1001 * operation is in progress.
1002 *
1003 * @param c the collection to transfer elements into
1004 * @return the number of elements transferred
1005 */
1006 protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
1007 int n = submissionQueue.drainTo(c);
1008 ForkJoinWorkerThread[] ws = workers;
1009 if (ws != null) {
1010 for (int i = 0; i < ws.length; ++i) {
1011 ForkJoinWorkerThread w = ws[i];
1012 if (w != null)
1013 n += w.drainTasksTo(c);
1014 }
1015 }
1016 return n;
1017 }
1018
1019 /**
1020 * Returns a string identifying this pool, as well as its state,
1021 * including indications of run state, parallelism level, and
1022 * worker and task counts.
1023 *
1024 * @return a string identifying this pool, as well as its state
1025 */
1026 public String toString() {
1027 int ps = parallelism;
1028 int wc = workerCounts;
1029 int rc = runControl;
1030 long st = getStealCount();
1031 long qt = getQueuedTaskCount();
1032 long qs = getQueuedSubmissionCount();
1033 return super.toString() +
1034 "[" + runStateToString(runStateOf(rc)) +
1035 ", parallelism = " + ps +
1036 ", size = " + totalCountOf(wc) +
1037 ", active = " + activeCountOf(rc) +
1038 ", running = " + runningCountOf(wc) +
1039 ", steals = " + st +
1040 ", tasks = " + qt +
1041 ", submissions = " + qs +
1042 "]";
1043 }
1044
1045 private static String runStateToString(int rs) {
1046 switch(rs) {
1047 case RUNNING: return "Running";
1048 case SHUTDOWN: return "Shutting down";
1049 case TERMINATING: return "Terminating";
1050 case TERMINATED: return "Terminated";
1051 default: throw new Error("Unknown run state");
1052 }
1053 }
1054
1055 // lifecycle control
1056
1057 /**
1058 * Initiates an orderly shutdown in which previously submitted
1059 * tasks are executed, but no new tasks will be accepted.
1060 * Invocation has no additional effect if already shut down.
1061 * Tasks that are in the process of being submitted concurrently
1062 * during the course of this method may or may not be rejected.
1063 *
1064 * @throws SecurityException if a security manager exists and
1065 * the caller is not permitted to modify threads
1066 * because it does not hold {@link
1067 * java.lang.RuntimePermission}{@code ("modifyThread")}
1068 */
1069 public void shutdown() {
1070 checkPermission();
1071 transitionRunStateTo(SHUTDOWN);
1072 if (canTerminateOnShutdown(runControl)) {
1073 if (workers == null) { // shutting down before workers created
1074 final ReentrantLock lock = this.workerLock;
1075 lock.lock();
1076 try {
1077 if (workers == null) {
1078 terminate();
1079 transitionRunStateTo(TERMINATED);
1080 termination.signalAll();
1081 }
1082 } finally {
1083 lock.unlock();
1084 }
1085 }
1086 terminateOnShutdown();
1087 }
1088 }
1089
1090 /**
1091 * Attempts to stop all actively executing tasks, and cancels all
1092 * waiting tasks. Tasks that are in the process of being
1093 * submitted or executed concurrently during the course of this
1094 * method may or may not be rejected. Unlike some other executors,
1095 * this method cancels rather than collects non-executed tasks
1096 * upon termination, so always returns an empty list. However, you
1097 * can use method {@link #drainTasksTo} before invoking this
1098 * method to transfer unexecuted tasks to another collection.
1099 *
1100 * @return an empty list
1101 * @throws SecurityException if a security manager exists and
1102 * the caller is not permitted to modify threads
1103 * because it does not hold {@link
1104 * java.lang.RuntimePermission}{@code ("modifyThread")}
1105 */
1106 public List<Runnable> shutdownNow() {
1107 checkPermission();
1108 terminate();
1109 return Collections.emptyList();
1110 }
1111
1112 /**
1113 * Returns {@code true} if all tasks have completed following shut down.
1114 *
1115 * @return {@code true} if all tasks have completed following shut down
1116 */
1117 public boolean isTerminated() {
1118 return runStateOf(runControl) == TERMINATED;
1119 }
1120
1121 /**
1122 * Returns {@code true} if the process of termination has
1123 * commenced but possibly not yet completed.
1124 *
1125 * @return {@code true} if terminating
1126 */
1127 public boolean isTerminating() {
1128 return runStateOf(runControl) >= TERMINATING;
1129 }
1130
1131 /**
1132 * Returns {@code true} if this pool has been shut down.
1133 *
1134 * @return {@code true} if this pool has been shut down
1135 */
1136 public boolean isShutdown() {
1137 return runStateOf(runControl) >= SHUTDOWN;
1138 }
1139
1140 /**
1141 * Blocks until all tasks have completed execution after a shutdown
1142 * request, or the timeout occurs, or the current thread is
1143 * interrupted, whichever happens first.
1144 *
1145 * @param timeout the maximum time to wait
1146 * @param unit the time unit of the timeout argument
1147 * @return {@code true} if this executor terminated and
1148 * {@code false} if the timeout elapsed before termination
1149 * @throws InterruptedException if interrupted while waiting
1150 */
1151 public boolean awaitTermination(long timeout, TimeUnit unit)
1152 throws InterruptedException {
1153 long nanos = unit.toNanos(timeout);
1154 final ReentrantLock lock = this.workerLock;
1155 lock.lock();
1156 try {
1157 for (;;) {
1158 if (isTerminated())
1159 return true;
1160 if (nanos <= 0)
1161 return false;
1162 nanos = termination.awaitNanos(nanos);
1163 }
1164 } finally {
1165 lock.unlock();
1166 }
1167 }
1168
1169 // Shutdown and termination support
1170
1171 /**
1172 * Callback from terminating worker. Nulls out the corresponding
1173 * workers slot, and if terminating, tries to terminate; else
1174 * tries to shrink workers array.
1175 *
1176 * @param w the worker
1177 */
1178 final void workerTerminated(ForkJoinWorkerThread w) {
1179 updateStealCount(w);
1180 updateWorkerCount(-1);
1181 final ReentrantLock lock = this.workerLock;
1182 lock.lock();
1183 try {
1184 ForkJoinWorkerThread[] ws = workers;
1185 if (ws != null) {
1186 int idx = w.poolIndex;
1187 if (idx >= 0 && idx < ws.length && ws[idx] == w)
1188 ws[idx] = null;
1189 if (totalCountOf(workerCounts) == 0) {
1190 terminate(); // no-op if already terminating
1191 transitionRunStateTo(TERMINATED);
1192 termination.signalAll();
1193 }
1194 else if (!isTerminating()) {
1195 tryShrinkWorkerArray();
1196 tryResumeSpare(true); // allow replacement
1197 }
1198 }
1199 } finally {
1200 lock.unlock();
1201 }
1202 signalIdleWorkers();
1203 }
1204
1205 /**
1206 * Initiates termination.
1207 */
1208 private void terminate() {
1209 if (transitionRunStateTo(TERMINATING)) {
1210 stopAllWorkers();
1211 resumeAllSpares();
1212 signalIdleWorkers();
1213 cancelQueuedSubmissions();
1214 cancelQueuedWorkerTasks();
1215 interruptUnterminatedWorkers();
1216 signalIdleWorkers(); // resignal after interrupt
1217 }
1218 }
1219
1220 /**
1221 * Possibly terminates when on shutdown state.
1222 */
1223 private void terminateOnShutdown() {
1224 if (!hasQueuedSubmissions() && canTerminateOnShutdown(runControl))
1225 terminate();
1226 }
1227
1228 /**
1229 * Clears out and cancels submissions.
1230 */
1231 private void cancelQueuedSubmissions() {
1232 ForkJoinTask<?> task;
1233 while ((task = pollSubmission()) != null)
1234 task.cancel(false);
1235 }
1236
1237 /**
1238 * Cleans out worker queues.
1239 */
1240 private void cancelQueuedWorkerTasks() {
1241 final ReentrantLock lock = this.workerLock;
1242 lock.lock();
1243 try {
1244 ForkJoinWorkerThread[] ws = workers;
1245 if (ws != null) {
1246 for (int i = 0; i < ws.length; ++i) {
1247 ForkJoinWorkerThread t = ws[i];
1248 if (t != null)
1249 t.cancelTasks();
1250 }
1251 }
1252 } finally {
1253 lock.unlock();
1254 }
1255 }
1256
1257 /**
1258 * Sets each worker's status to terminating. Requires lock to avoid
1259 * conflicts with add/remove.
1260 */
1261 private void stopAllWorkers() {
1262 final ReentrantLock lock = this.workerLock;
1263 lock.lock();
1264 try {
1265 ForkJoinWorkerThread[] ws = workers;
1266 if (ws != null) {
1267 for (int i = 0; i < ws.length; ++i) {
1268 ForkJoinWorkerThread t = ws[i];
1269 if (t != null)
1270 t.shutdownNow();
1271 }
1272 }
1273 } finally {
1274 lock.unlock();
1275 }
1276 }
1277
1278 /**
1279 * Interrupts all unterminated workers. This is not required for
1280 * sake of internal control, but may help unstick user code during
1281 * shutdown.
1282 */
1283 private void interruptUnterminatedWorkers() {
1284 final ReentrantLock lock = this.workerLock;
1285 lock.lock();
1286 try {
1287 ForkJoinWorkerThread[] ws = workers;
1288 if (ws != null) {
1289 for (int i = 0; i < ws.length; ++i) {
1290 ForkJoinWorkerThread t = ws[i];
1291 if (t != null && !t.isTerminated()) {
1292 try {
1293 t.interrupt();
1294 } catch (SecurityException ignore) {
1295 }
1296 }
1297 }
1298 }
1299 } finally {
1300 lock.unlock();
1301 }
1302 }
1303
1304
1305 /*
1306 * Nodes for event barrier to manage idle threads. Queue nodes
1307 * are basic Treiber stack nodes, also used for spare stack.
1308 *
1309 * The event barrier has an event count and a wait queue (actually
1310 * a Treiber stack). Workers are enabled to look for work when
1311 * the eventCount is incremented. If they fail to find work, they
1312 * may wait for next count. Upon release, threads help others wake
1313 * up.
1314 *
1315 * Synchronization events occur only in enough contexts to
1316 * maintain overall liveness:
1317 *
1318 * - Submission of a new task to the pool
1319 * - Resizes or other changes to the workers array
1320 * - pool termination
1321 * - A worker pushing a task on an empty queue
1322 *
1323 * The case of pushing a task occurs often enough, and is heavy
1324 * enough compared to simple stack pushes, to require special
1325 * handling: Method signalWork returns without advancing count if
1326 * the queue appears to be empty. This would ordinarily result in
1327 * races causing some queued waiters not to be woken up. To avoid
1328 * this, the first worker enqueued in method sync (see
1329 * syncIsReleasable) rescans for tasks after being enqueued, and
1330 * helps signal if any are found. This works well because the
1331 * worker has nothing better to do, and so might as well help
1332 * alleviate the overhead and contention on the threads actually
1333 * doing work. Also, since event counts increments on task
1334 * availability exist to maintain liveness (rather than to force
1335 * refreshes etc), it is OK for callers to exit early if
1336 * contending with another signaller.
1337 */
1338 static final class WaitQueueNode {
1339 WaitQueueNode next; // only written before enqueued
1340 volatile ForkJoinWorkerThread thread; // nulled to cancel wait
1341 final long count; // unused for spare stack
1342
1343 WaitQueueNode(long c, ForkJoinWorkerThread w) {
1344 count = c;
1345 thread = w;
1346 }
1347
1348 /**
1349 * Wakes up waiter, returning false if known to already
1350 */
1351 boolean signal() {
1352 ForkJoinWorkerThread t = thread;
1353 if (t == null)
1354 return false;
1355 thread = null;
1356 LockSupport.unpark(t);
1357 return true;
1358 }
1359
1360 /**
1361 * Awaits release on sync.
1362 */
1363 void awaitSyncRelease(ForkJoinPool p) {
1364 while (thread != null && !p.syncIsReleasable(this))
1365 LockSupport.park(this);
1366 }
1367
1368 /**
1369 * Awaits resumption as spare.
1370 */
1371 void awaitSpareRelease() {
1372 while (thread != null) {
1373 if (!Thread.interrupted())
1374 LockSupport.park(this);
1375 }
1376 }
1377 }
1378
1379 /**
1380 * Ensures that no thread is waiting for count to advance from the
1381 * current value of eventCount read on entry to this method, by
1382 * releasing waiting threads if necessary.
1383 *
1384 * @return the count
1385 */
1386 final long ensureSync() {
1387 long c = eventCount;
1388 WaitQueueNode q;
1389 while ((q = syncStack) != null && q.count < c) {
1390 if (casBarrierStack(q, null)) {
1391 do {
1392 q.signal();
1393 } while ((q = q.next) != null);
1394 break;
1395 }
1396 }
1397 return c;
1398 }
1399
1400 /**
1401 * Increments event count and releases waiting threads.
1402 */
1403 private void signalIdleWorkers() {
1404 long c;
1405 do {} while (!casEventCount(c = eventCount, c+1));
1406 ensureSync();
1407 }
1408
1409 /**
1410 * Signals threads waiting to poll a task. Because method sync
1411 * rechecks availability, it is OK to only proceed if queue
1412 * appears to be non-empty, and OK to skip under contention to
1413 * increment count (since some other thread succeeded).
1414 */
1415 final void signalWork() {
1416 long c;
1417 WaitQueueNode q;
1418 if (syncStack != null &&
1419 casEventCount(c = eventCount, c+1) &&
1420 (((q = syncStack) != null && q.count <= c) &&
1421 (!casBarrierStack(q, q.next) || !q.signal())))
1422 ensureSync();
1423 }
1424
1425 /**
1426 * Waits until event count advances from last value held by
1427 * caller, or if excess threads, caller is resumed as spare, or
1428 * caller or pool is terminating. Updates caller's event on exit.
1429 *
1430 * @param w the calling worker thread
1431 */
1432 final void sync(ForkJoinWorkerThread w) {
1433 updateStealCount(w); // Transfer w's count while it is idle
1434
1435 while (!w.isShutdown() && !isTerminating() && !suspendIfSpare(w)) {
1436 long prev = w.lastEventCount;
1437 WaitQueueNode node = null;
1438 WaitQueueNode h;
1439 while (eventCount == prev &&
1440 ((h = syncStack) == null || h.count == prev)) {
1441 if (node == null)
1442 node = new WaitQueueNode(prev, w);
1443 if (casBarrierStack(node.next = h, node)) {
1444 node.awaitSyncRelease(this);
1445 break;
1446 }
1447 }
1448 long ec = ensureSync();
1449 if (ec != prev) {
1450 w.lastEventCount = ec;
1451 break;
1452 }
1453 }
1454 }
1455
1456 /**
1457 * Returns {@code true} if worker waiting on sync can proceed:
1458 * - on signal (thread == null)
1459 * - on event count advance (winning race to notify vs signaller)
1460 * - on interrupt
1461 * - if the first queued node, we find work available
1462 * If node was not signalled and event count not advanced on exit,
1463 * then we also help advance event count.
1464 *
1465 * @return {@code true} if node can be released
1466 */
1467 final boolean syncIsReleasable(WaitQueueNode node) {
1468 long prev = node.count;
1469 if (!Thread.interrupted() && node.thread != null &&
1470 (node.next != null ||
1471 !ForkJoinWorkerThread.hasQueuedTasks(workers)) &&
1472 eventCount == prev)
1473 return false;
1474 if (node.thread != null) {
1475 node.thread = null;
1476 long ec = eventCount;
1477 if (prev <= ec) // help signal
1478 casEventCount(ec, ec+1);
1479 }
1480 return true;
1481 }
1482
1483 /**
1484 * Returns {@code true} if a new sync event occurred since last
1485 * call to sync or this method, if so, updating caller's count.
1486 */
1487 final boolean hasNewSyncEvent(ForkJoinWorkerThread w) {
1488 long lc = w.lastEventCount;
1489 long ec = ensureSync();
1490 if (ec == lc)
1491 return false;
1492 w.lastEventCount = ec;
1493 return true;
1494 }
1495
1496 // Parallelism maintenance
1497
1498 /**
1499 * Decrements running count; if too low, adds spare.
1500 *
1501 * Conceptually, all we need to do here is add or resume a
1502 * spare thread when one is about to block (and remove or
1503 * suspend it later when unblocked -- see suspendIfSpare).
1504 * However, implementing this idea requires coping with
1505 * several problems: we have imperfect information about the
1506 * states of threads. Some count updates can and usually do
1507 * lag run state changes, despite arrangements to keep them
1508 * accurate (for example, when possible, updating counts
1509 * before signalling or resuming), especially when running on
1510 * dynamic JVMs that don't optimize the infrequent paths that
1511 * update counts. Generating too many threads can make these
1512 * problems become worse, because excess threads are more
1513 * likely to be context-switched with others, slowing them all
1514 * down, especially if there is no work available, so all are
1515 * busy scanning or idling. Also, excess spare threads can
1516 * only be suspended or removed when they are idle, not
1517 * immediately when they aren't needed. So adding threads will
1518 * raise parallelism level for longer than necessary. Also,
1519 * FJ applications often encounter highly transient peaks when
1520 * many threads are blocked joining, but for less time than it
1521 * takes to create or resume spares.
1522 *
1523 * @param joinMe if non-null, return early if done
1524 * @param maintainParallelism if true, try to stay within
1525 * target counts, else create only to avoid starvation
1526 * @return true if joinMe known to be done
1527 */
1528 final boolean preJoin(ForkJoinTask<?> joinMe,
1529 boolean maintainParallelism) {
1530 maintainParallelism &= maintainsParallelism; // overrride
1531 boolean dec = false; // true when running count decremented
1532 while (spareStack == null || !tryResumeSpare(dec)) {
1533 int counts = workerCounts;
1534 if (dec || (dec = casWorkerCounts(counts, --counts))) {
1535 // CAS cheat
1536 if (!needSpare(counts, maintainParallelism))
1537 break;
1538 if (joinMe.status < 0)
1539 return true;
1540 if (tryAddSpare(counts))
1541 break;
1542 }
1543 }
1544 return false;
1545 }
1546
1547 /**
1548 * Same idea as preJoin
1549 */
1550 final boolean preBlock(ManagedBlocker blocker,
1551 boolean maintainParallelism) {
1552 maintainParallelism &= maintainsParallelism;
1553 boolean dec = false;
1554 while (spareStack == null || !tryResumeSpare(dec)) {
1555 int counts = workerCounts;
1556 if (dec || (dec = casWorkerCounts(counts, --counts))) {
1557 if (!needSpare(counts, maintainParallelism))
1558 break;
1559 if (blocker.isReleasable())
1560 return true;
1561 if (tryAddSpare(counts))
1562 break;
1563 }
1564 }
1565 return false;
1566 }
1567
1568 /**
1569 * Returns {@code true} if a spare thread appears to be needed.
1570 * If maintaining parallelism, returns true when the deficit in
1571 * running threads is more than the surplus of total threads, and
1572 * there is apparently some work to do. This self-limiting rule
1573 * means that the more threads that have already been added, the
1574 * less parallelism we will tolerate before adding another.
1575 *
1576 * @param counts current worker counts
1577 * @param maintainParallelism try to maintain parallelism
1578 */
1579 private boolean needSpare(int counts, boolean maintainParallelism) {
1580 int ps = parallelism;
1581 int rc = runningCountOf(counts);
1582 int tc = totalCountOf(counts);
1583 int runningDeficit = ps - rc;
1584 int totalSurplus = tc - ps;
1585 return (tc < maxPoolSize &&
1586 (rc == 0 || totalSurplus < 0 ||
1587 (maintainParallelism &&
1588 runningDeficit > totalSurplus &&
1589 ForkJoinWorkerThread.hasQueuedTasks(workers))));
1590 }
1591
1592 /**
1593 * Adds a spare worker if lock available and no more than the
1594 * expected numbers of threads exist.
1595 *
1596 * @return true if successful
1597 */
1598 private boolean tryAddSpare(int expectedCounts) {
1599 final ReentrantLock lock = this.workerLock;
1600 int expectedRunning = runningCountOf(expectedCounts);
1601 int expectedTotal = totalCountOf(expectedCounts);
1602 boolean success = false;
1603 boolean locked = false;
1604 // confirm counts while locking; CAS after obtaining lock
1605 try {
1606 for (;;) {
1607 int s = workerCounts;
1608 int tc = totalCountOf(s);
1609 int rc = runningCountOf(s);
1610 if (rc > expectedRunning || tc > expectedTotal)
1611 break;
1612 if (!locked && !(locked = lock.tryLock()))
1613 break;
1614 if (casWorkerCounts(s, workerCountsFor(tc+1, rc+1))) {
1615 createAndStartSpare(tc);
1616 success = true;
1617 break;
1618 }
1619 }
1620 } finally {
1621 if (locked)
1622 lock.unlock();
1623 }
1624 return success;
1625 }
1626
1627 /**
1628 * Adds the kth spare worker. On entry, pool counts are already
1629 * adjusted to reflect addition.
1630 */
1631 private void createAndStartSpare(int k) {
1632 ForkJoinWorkerThread w = null;
1633 ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(k + 1);
1634 int len = ws.length;
1635 // Probably, we can place at slot k. If not, find empty slot
1636 if (k < len && ws[k] != null) {
1637 for (k = 0; k < len && ws[k] != null; ++k)
1638 ;
1639 }
1640 if (k < len && !isTerminating() && (w = createWorker(k)) != null) {
1641 ws[k] = w;
1642 w.start();
1643 }
1644 else
1645 updateWorkerCount(-1); // adjust on failure
1646 signalIdleWorkers();
1647 }
1648
1649 /**
1650 * Suspends calling thread w if there are excess threads. Called
1651 * only from sync. Spares are enqueued in a Treiber stack using
1652 * the same WaitQueueNodes as barriers. They are resumed mainly
1653 * in preJoin, but are also woken on pool events that require all
1654 * threads to check run state.
1655 *
1656 * @param w the caller
1657 */
1658 private boolean suspendIfSpare(ForkJoinWorkerThread w) {
1659 WaitQueueNode node = null;
1660 int s;
1661 while (parallelism < runningCountOf(s = workerCounts)) {
1662 if (node == null)
1663 node = new WaitQueueNode(0, w);
1664 if (casWorkerCounts(s, s-1)) { // representation-dependent
1665 // push onto stack
1666 do {} while (!casSpareStack(node.next = spareStack, node));
1667 // block until released by resumeSpare
1668 node.awaitSpareRelease();
1669 return true;
1670 }
1671 }
1672 return false;
1673 }
1674
1675 /**
1676 * Tries to pop and resume a spare thread.
1677 *
1678 * @param updateCount if true, increment running count on success
1679 * @return true if successful
1680 */
1681 private boolean tryResumeSpare(boolean updateCount) {
1682 WaitQueueNode q;
1683 while ((q = spareStack) != null) {
1684 if (casSpareStack(q, q.next)) {
1685 if (updateCount)
1686 updateRunningCount(1);
1687 q.signal();
1688 return true;
1689 }
1690 }
1691 return false;
1692 }
1693
1694 /**
1695 * Pops and resumes all spare threads. Same idea as ensureSync.
1696 *
1697 * @return true if any spares released
1698 */
1699 private boolean resumeAllSpares() {
1700 WaitQueueNode q;
1701 while ( (q = spareStack) != null) {
1702 if (casSpareStack(q, null)) {
1703 do {
1704 updateRunningCount(1);
1705 q.signal();
1706 } while ((q = q.next) != null);
1707 return true;
1708 }
1709 }
1710 return false;
1711 }
1712
1713 /**
1714 * Pops and shuts down excessive spare threads. Call only while
1715 * holding lock. This is not guaranteed to eliminate all excess
1716 * threads, only those suspended as spares, which are the ones
1717 * unlikely to be needed in the future.
1718 */
1719 private void trimSpares() {
1720 int surplus = totalCountOf(workerCounts) - parallelism;
1721 WaitQueueNode q;
1722 while (surplus > 0 && (q = spareStack) != null) {
1723 if (casSpareStack(q, null)) {
1724 do {
1725 updateRunningCount(1);
1726 ForkJoinWorkerThread w = q.thread;
1727 if (w != null && surplus > 0 &&
1728 runningCountOf(workerCounts) > 0 && w.shutdown())
1729 --surplus;
1730 q.signal();
1731 } while ((q = q.next) != null);
1732 }
1733 }
1734 }
1735
1736 /**
1737 * Interface for extending managed parallelism for tasks running
1738 * in ForkJoinPools. A ManagedBlocker provides two methods.
1739 * Method {@code isReleasable} must return {@code true} if
1740 * blocking is not necessary. Method {@code block} blocks the
1741 * current thread if necessary (perhaps internally invoking
1742 * {@code isReleasable} before actually blocking.).
1743 *
1744 * <p>For example, here is a ManagedBlocker based on a
1745 * ReentrantLock:
1746 * <pre> {@code
1747 * class ManagedLocker implements ManagedBlocker {
1748 * final ReentrantLock lock;
1749 * boolean hasLock = false;
1750 * ManagedLocker(ReentrantLock lock) { this.lock = lock; }
1751 * public boolean block() {
1752 * if (!hasLock)
1753 * lock.lock();
1754 * return true;
1755 * }
1756 * public boolean isReleasable() {
1757 * return hasLock || (hasLock = lock.tryLock());
1758 * }
1759 * }}</pre>
1760 */
1761 public static interface ManagedBlocker {
1762 /**
1763 * Possibly blocks the current thread, for example waiting for
1764 * a lock or condition.
1765 *
1766 * @return {@code true} if no additional blocking is necessary
1767 * (i.e., if isReleasable would return true)
1768 * @throws InterruptedException if interrupted while waiting
1769 * (the method is not required to do so, but is allowed to)
1770 */
1771 boolean block() throws InterruptedException;
1772
1773 /**
1774 * Returns {@code true} if blocking is unnecessary.
1775 */
1776 boolean isReleasable();
1777 }
1778
1779 /**
1780 * Blocks in accord with the given blocker. If the current thread
1781 * is a ForkJoinWorkerThread, this method possibly arranges for a
1782 * spare thread to be activated if necessary to ensure parallelism
1783 * while the current thread is blocked. If
1784 * {@code maintainParallelism} is {@code true} and the pool supports
1785 * it ({@link #getMaintainsParallelism}), this method attempts to
1786 * maintain the pool's nominal parallelism. Otherwise it activates
1787 * a thread only if necessary to avoid complete starvation. This
1788 * option may be preferable when blockages use timeouts, or are
1789 * almost always brief.
1790 *
1791 * <p> If the caller is not a ForkJoinTask, this method is behaviorally
1792 * equivalent to
1793 * <pre> {@code
1794 * while (!blocker.isReleasable())
1795 * if (blocker.block())
1796 * return;
1797 * }</pre>
1798 * If the caller is a ForkJoinTask, then the pool may first
1799 * be expanded to ensure parallelism, and later adjusted.
1800 *
1801 * @param blocker the blocker
1802 * @param maintainParallelism if {@code true} and supported by
1803 * this pool, attempt to maintain the pool's nominal parallelism;
1804 * otherwise activate a thread only if necessary to avoid
1805 * complete starvation.
1806 * @throws InterruptedException if blocker.block did so
1807 */
1808 public static void managedBlock(ManagedBlocker blocker,
1809 boolean maintainParallelism)
1810 throws InterruptedException {
1811 Thread t = Thread.currentThread();
1812 ForkJoinPool pool = ((t instanceof ForkJoinWorkerThread) ?
1813 ((ForkJoinWorkerThread) t).pool : null);
1814 if (!blocker.isReleasable()) {
1815 try {
1816 if (pool == null ||
1817 !pool.preBlock(blocker, maintainParallelism))
1818 awaitBlocker(blocker);
1819 } finally {
1820 if (pool != null)
1821 pool.updateRunningCount(1);
1822 }
1823 }
1824 }
1825
1826 private static void awaitBlocker(ManagedBlocker blocker)
1827 throws InterruptedException {
1828 do {} while (!blocker.isReleasable() && !blocker.block());
1829 }
1830
1831 // AbstractExecutorService overrides. These rely on undocumented
1832 // fact that ForkJoinTask.adapt returns ForkJoinTasks that also
1833 // implement RunnableFuture.
1834
1835 protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
1836 return (RunnableFuture<T>)ForkJoinTask.adapt(runnable, value);
1837 }
1838
1839 protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
1840 return (RunnableFuture<T>)ForkJoinTask.adapt(callable);
1841 }
1842
1843 // Unsafe mechanics
1844
1845 private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1846 private static final long eventCountOffset =
1847 objectFieldOffset("eventCount", ForkJoinPool.class);
1848 private static final long workerCountsOffset =
1849 objectFieldOffset("workerCounts", ForkJoinPool.class);
1850 private static final long runControlOffset =
1851 objectFieldOffset("runControl", ForkJoinPool.class);
1852 private static final long syncStackOffset =
1853 objectFieldOffset("syncStack",ForkJoinPool.class);
1854 private static final long spareStackOffset =
1855 objectFieldOffset("spareStack", ForkJoinPool.class);
1856
1857 private boolean casEventCount(long cmp, long val) {
1858 return UNSAFE.compareAndSwapLong(this, eventCountOffset, cmp, val);
1859 }
1860 private boolean casWorkerCounts(int cmp, int val) {
1861 return UNSAFE.compareAndSwapInt(this, workerCountsOffset, cmp, val);
1862 }
1863 private boolean casRunControl(int cmp, int val) {
1864 return UNSAFE.compareAndSwapInt(this, runControlOffset, cmp, val);
1865 }
1866 private boolean casSpareStack(WaitQueueNode cmp, WaitQueueNode val) {
1867 return UNSAFE.compareAndSwapObject(this, spareStackOffset, cmp, val);
1868 }
1869 private boolean casBarrierStack(WaitQueueNode cmp, WaitQueueNode val) {
1870 return UNSAFE.compareAndSwapObject(this, syncStackOffset, cmp, val);
1871 }
1872
1873 private static long objectFieldOffset(String field, Class<?> klazz) {
1874 try {
1875 return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1876 } catch (NoSuchFieldException e) {
1877 // Convert Exception to corresponding Error
1878 NoSuchFieldError error = new NoSuchFieldError(field);
1879 error.initCause(e);
1880 throw error;
1881 }
1882 }
1883
1884 /**
1885 * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
1886 * Replace with a simple call to Unsafe.getUnsafe when integrating
1887 * into a jdk.
1888 *
1889 * @return a sun.misc.Unsafe
1890 */
1891 private static sun.misc.Unsafe getUnsafe() {
1892 try {
1893 return sun.misc.Unsafe.getUnsafe();
1894 } catch (SecurityException se) {
1895 try {
1896 return java.security.AccessController.doPrivileged
1897 (new java.security
1898 .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1899 public sun.misc.Unsafe run() throws Exception {
1900 java.lang.reflect.Field f = sun.misc
1901 .Unsafe.class.getDeclaredField("theUnsafe");
1902 f.setAccessible(true);
1903 return (sun.misc.Unsafe) f.get(null);
1904 }});
1905 } catch (java.security.PrivilegedActionException e) {
1906 throw new RuntimeException("Could not initialize intrinsics",
1907 e.getCause());
1908 }
1909 }
1910 }
1911 }