ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinPool.java
Revision: 1.16
Committed: Thu Jul 23 19:44:46 2009 UTC (14 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.15: +97 -94 lines
Log Message:
merge lost changes

File Contents

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