ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinPool.java
Revision: 1.10
Committed: Mon Jul 20 23:07:43 2009 UTC (14 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.9: +31 -31 lines
Log Message:
third person in first sentence

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