ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.7
Committed: Fri Jul 31 20:41:13 2009 UTC (14 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.6: +10 -62 lines
Log Message:
sync with jsr166 package

File Contents

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