ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinPool.java
Revision: 1.5
Committed: Thu Mar 19 05:10:42 2009 UTC (15 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.4: +40 -23 lines
Log Message:
getUnsafe should use doPrivileged

File Contents

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