ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.9
Committed: Tue Aug 4 01:23:41 2009 UTC (14 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.8: +99 -58 lines
Log Message:
sync with jsr166 package

File Contents

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