ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.1
Committed: Sat Jul 25 01:06:20 2009 UTC (14 years, 10 months ago) by jsr166
Branch: MAIN
Log Message:
branch jsr166y into java.util.concurrent

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