ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinPool.java
Revision: 1.2
Committed: Wed Jan 7 16:07:37 2009 UTC (15 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.1: +130 -129 lines
Log Message:
Improved documentaion; moved methods to improve javadoc flow; regularized extension APIs

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