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