ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinPool.java
Revision: 1.21
Committed: Fri Jul 24 23:47:01 2009 UTC (14 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.20: +31 -34 lines
Log Message:
Unsafe mechanics

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