ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinPool.java
Revision: 1.1
Committed: Tue Jan 6 14:30:31 2009 UTC (15 years, 4 months ago) by dl
Branch: MAIN
Log Message:
Refactored and repackaged ForkJoin classes

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