21 |
|
|
22 |
|
/** |
23 |
|
* An {@link ExecutorService} for running {@link ForkJoinTask}s. |
24 |
< |
* A ForkJoinPool provides the entry point for submissions from |
25 |
< |
* non-ForkJoinTasks, as well as management and monitoring operations. |
26 |
< |
* Normally a single ForkJoinPool is used for a large number of |
27 |
< |
* submitted tasks. Otherwise, use would not usually outweigh the |
28 |
< |
* construction and bookkeeping overhead of creating a large set of |
29 |
< |
* threads. |
24 |
> |
* A {@code ForkJoinPool} provides the entry point for submissions |
25 |
> |
* from non-{@code ForkJoinTask}s, as well as management and |
26 |
> |
* monitoring operations. |
27 |
|
* |
28 |
< |
* <p>ForkJoinPools differ from other kinds of Executors mainly in |
29 |
< |
* that they provide <em>work-stealing</em>: all threads in the pool |
30 |
< |
* attempt to find and execute subtasks created by other active tasks |
31 |
< |
* (eventually blocking if none exist). This makes them efficient when |
32 |
< |
* most tasks spawn other subtasks (as do most ForkJoinTasks), as well |
33 |
< |
* as the mixed execution of some plain Runnable- or Callable- based |
34 |
< |
* activities along with ForkJoinTasks. When setting {@linkplain |
35 |
< |
* #setAsyncMode async mode}, a ForkJoinPool may also be appropriate |
36 |
< |
* for use with fine-grained tasks that are never joined. Otherwise, |
37 |
< |
* other ExecutorService implementations are typically more |
38 |
< |
* appropriate choices. |
28 |
> |
* <p>A {@code ForkJoinPool} differs from other kinds of {@link |
29 |
> |
* ExecutorService} mainly by virtue of employing |
30 |
> |
* <em>work-stealing</em>: all threads in the pool attempt to find and |
31 |
> |
* execute subtasks created by other active tasks (eventually blocking |
32 |
> |
* waiting for work if none exist). This enables efficient processing |
33 |
> |
* when most tasks spawn other subtasks (as do most {@code |
34 |
> |
* ForkJoinTask}s). A {@code ForkJoinPool} may also be used for mixed |
35 |
> |
* execution of some plain {@code Runnable}- or {@code Callable}- |
36 |
> |
* based activities along with {@code ForkJoinTask}s. When setting |
37 |
> |
* {@linkplain #setAsyncMode async mode}, a {@code ForkJoinPool} may |
38 |
> |
* also be appropriate for use with fine-grained tasks of any form |
39 |
> |
* that are never joined. Otherwise, other {@code ExecutorService} |
40 |
> |
* implementations are typically more appropriate choices. |
41 |
|
* |
42 |
< |
* <p>A ForkJoinPool may be constructed with a given parallelism level |
43 |
< |
* (target pool size), which it attempts to maintain by dynamically |
44 |
< |
* adding, suspending, or resuming threads, even if some tasks are |
45 |
< |
* waiting to join others. However, no such adjustments are performed |
46 |
< |
* in the face of blocked IO or other unmanaged synchronization. The |
47 |
< |
* nested {@link ManagedBlocker} interface enables extension of |
48 |
< |
* the kinds of synchronization accommodated. The target parallelism |
49 |
< |
* level may also be changed dynamically ({@link #setParallelism}) |
50 |
< |
* and thread construction can be limited using methods |
51 |
< |
* {@link #setMaximumPoolSize} and/or |
52 |
< |
* {@link #setMaintainsParallelism}. |
42 |
> |
* <p>A {@code ForkJoinPool} is constructed with a given target |
43 |
> |
* parallelism level; by default, equal to the number of available |
44 |
> |
* processors. Unless configured otherwise via {@link |
45 |
> |
* #setMaintainsParallelism}, the pool attempts to maintain this |
46 |
> |
* number of active (or available) threads by dynamically adding, |
47 |
> |
* suspending, or resuming internal worker threads, even if some tasks |
48 |
> |
* are waiting to join others. However, no such adjustments are |
49 |
> |
* performed in the face of blocked IO or other unmanaged |
50 |
> |
* synchronization. The nested {@link ManagedBlocker} interface |
51 |
> |
* enables extension of the kinds of synchronization accommodated. |
52 |
> |
* The target parallelism level may also be changed dynamically |
53 |
> |
* ({@link #setParallelism}). The total number of threads may be |
54 |
> |
* limited using method {@link #setMaximumPoolSize}, in which case it |
55 |
> |
* may become possible for the activities of a pool to stall due to |
56 |
> |
* the lack of available threads to process new tasks. |
57 |
|
* |
58 |
|
* <p>In addition to execution and lifecycle control methods, this |
59 |
|
* class provides status check methods (for example |
62 |
|
* {@link #toString} returns indications of pool state in a |
63 |
|
* convenient form for informal monitoring. |
64 |
|
* |
65 |
+ |
* <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is |
66 |
+ |
* used for all parallel task execution in a program or subsystem. |
67 |
+ |
* Otherwise, use would not usually outweigh the construction and |
68 |
+ |
* bookkeeping overhead of creating a large set of threads. For |
69 |
+ |
* example a common pool could be used for the {@code SortTasks} |
70 |
+ |
* illustrated in {@link RecursiveAction}. Because {@code |
71 |
+ |
* ForkJoinPool} uses threads in {@linkplain java.lang.Thread#isDaemon |
72 |
+ |
* daemon} mode, there is typically no need to explictly {@link |
73 |
+ |
* #shutdown} such a pool upon program exit. |
74 |
+ |
* |
75 |
+ |
* <pre> |
76 |
+ |
* static final ForkJoinPool mainPool = new ForkJoinPool(); |
77 |
+ |
* ... |
78 |
+ |
* public void sort(long[] array) { |
79 |
+ |
* mainPool.invoke(new SortTask(array, 0, array.length)); |
80 |
+ |
* } |
81 |
+ |
* </pre> |
82 |
+ |
* |
83 |
|
* <p><b>Implementation notes</b>: This implementation restricts the |
84 |
|
* maximum number of running threads to 32767. Attempts to create |
85 |
|
* pools with greater than the maximum result in |
86 |
< |
* IllegalArgumentExceptions. |
86 |
> |
* {@code IllegalArgumentException}. |
87 |
|
* |
88 |
|
* @since 1.7 |
89 |
|
* @author Doug Lea |
363 |
|
// Constructors |
364 |
|
|
365 |
|
/** |
366 |
< |
* Creates a ForkJoinPool with a pool size equal to the number of |
367 |
< |
* processors available on the system, using the default |
368 |
< |
* ForkJoinWorkerThreadFactory. |
366 |
> |
* Creates a {@code ForkJoinPool} with parallelism equal to {@link |
367 |
> |
* java.lang.Runtime#availableProcessors}, and using the {@linkplain |
368 |
> |
* #defaultForkJoinWorkerThreadFactory default thread factory}. |
369 |
|
* |
370 |
|
* @throws SecurityException if a security manager exists and |
371 |
|
* the caller is not permitted to modify threads |
378 |
|
} |
379 |
|
|
380 |
|
/** |
381 |
< |
* Creates a ForkJoinPool with the indicated parallelism level |
382 |
< |
* threads and using the default ForkJoinWorkerThreadFactory. |
381 |
> |
* Creates a {@code ForkJoinPool} with the indicated parallelism |
382 |
> |
* level and using the {@linkplain |
383 |
> |
* #defaultForkJoinWorkerThreadFactory default thread factory}. |
384 |
|
* |
385 |
< |
* @param parallelism the number of worker threads |
385 |
> |
* @param parallelism the parallelism level |
386 |
|
* @throws IllegalArgumentException if parallelism less than or |
387 |
|
* equal to zero |
388 |
|
* @throws SecurityException if a security manager exists and |
395 |
|
} |
396 |
|
|
397 |
|
/** |
398 |
< |
* Creates a ForkJoinPool with parallelism equal to the number of |
399 |
< |
* processors available on the system and using the given |
400 |
< |
* ForkJoinWorkerThreadFactory. |
398 |
> |
* Creates a {@code ForkJoinPool} with parallelism equal to {@link |
399 |
> |
* java.lang.Runtime#availableProcessors}, and using the given |
400 |
> |
* thread factory. |
401 |
|
* |
402 |
|
* @param factory the factory for creating new threads |
403 |
|
* @throws NullPointerException if factory is null |
411 |
|
} |
412 |
|
|
413 |
|
/** |
414 |
< |
* Creates a ForkJoinPool with the given parallelism and factory. |
414 |
> |
* Creates a {@code ForkJoinPool} with the given parallelism and |
415 |
> |
* thread factory. |
416 |
|
* |
417 |
< |
* @param parallelism the targeted number of worker threads |
417 |
> |
* @param parallelism the parallelism level |
418 |
|
* @param factory the factory for creating new threads |
419 |
|
* @throws IllegalArgumentException if parallelism less than or |
420 |
|
* equal to zero, or greater than implementation limit |
446 |
|
* Creates a new worker thread using factory. |
447 |
|
* |
448 |
|
* @param index the index to assign worker |
449 |
< |
* @return new worker, or null of factory failed |
449 |
> |
* @return new worker, or null if factory failed |
450 |
|
*/ |
451 |
|
private ForkJoinWorkerThread createWorker(int index) { |
452 |
|
Thread.UncaughtExceptionHandler h = ueh; |
467 |
|
* Currently requires size to be a power of two. |
468 |
|
*/ |
469 |
|
private static int arraySizeFor(int poolSize) { |
470 |
< |
return (poolSize <= 1) ? 1 : |
471 |
< |
(1 << (32 - Integer.numberOfLeadingZeros(poolSize-1))); |
470 |
> |
if (poolSize <= 1) |
471 |
> |
return 1; |
472 |
> |
// See Hackers Delight, sec 3.2 |
473 |
> |
int c = poolSize >= MAX_THREADS ? MAX_THREADS : (poolSize - 1); |
474 |
> |
c |= c >>> 1; |
475 |
> |
c |= c >>> 2; |
476 |
> |
c |= c >>> 4; |
477 |
> |
c |= c >>> 8; |
478 |
> |
c |= c >>> 16; |
479 |
> |
return c + 1; |
480 |
|
} |
481 |
|
|
482 |
|
/** |
609 |
|
* @throws NullPointerException if task is null |
610 |
|
* @throws RejectedExecutionException if pool is shut down |
611 |
|
*/ |
612 |
< |
public <T> void execute(ForkJoinTask<T> task) { |
612 |
> |
public void execute(ForkJoinTask<?> task) { |
613 |
|
doSubmit(task); |
614 |
|
} |
615 |
|
|
767 |
|
final ReentrantLock lock = this.workerLock; |
768 |
|
lock.lock(); |
769 |
|
try { |
770 |
< |
if (!isTerminating()) { |
770 |
> |
if (isProcessingTasks()) { |
771 |
|
int p = this.parallelism; |
772 |
|
this.parallelism = parallelism; |
773 |
|
if (parallelism > p) |
782 |
|
} |
783 |
|
|
784 |
|
/** |
785 |
< |
* Returns the targeted number of worker threads in this pool. |
785 |
> |
* Returns the targeted parallelism level of this pool. |
786 |
|
* |
787 |
< |
* @return the targeted number of worker threads in this pool |
787 |
> |
* @return the targeted parallelism level of this pool |
788 |
|
*/ |
789 |
|
public int getParallelism() { |
790 |
|
return parallelism; |
804 |
|
|
805 |
|
/** |
806 |
|
* Returns the maximum number of threads allowed to exist in the |
807 |
< |
* pool, even if there are insufficient unblocked running threads. |
807 |
> |
* pool. Unless set using {@link #setMaximumPoolSize}, the |
808 |
> |
* maximum is an implementation-defined value designed only to |
809 |
> |
* prevent runaway growth. |
810 |
|
* |
811 |
|
* @return the maximum |
812 |
|
*/ |
816 |
|
|
817 |
|
/** |
818 |
|
* Sets the maximum number of threads allowed to exist in the |
819 |
< |
* pool, even if there are insufficient unblocked running threads. |
820 |
< |
* Setting this value has no effect on current pool size. It |
788 |
< |
* controls construction of new threads. |
819 |
> |
* pool. Setting this value has no effect on current pool |
820 |
> |
* size. It controls construction of new threads. |
821 |
|
* |
822 |
|
* @throws IllegalArgumentException if negative or greater than |
823 |
|
* internal implementation limit |
987 |
|
} |
988 |
|
|
989 |
|
/** |
990 |
< |
* Returns an estimate of the number tasks submitted to this pool |
991 |
< |
* that have not yet begun executing. This method takes time |
990 |
> |
* Returns an estimate of the number of tasks submitted to this |
991 |
> |
* pool that have not yet begun executing. This method takes time |
992 |
|
* proportional to the number of submissions. |
993 |
|
* |
994 |
|
* @return the number of queued submissions |
1022 |
|
* Removes all available unexecuted submitted and forked tasks |
1023 |
|
* from scheduling queues and adds them to the given collection, |
1024 |
|
* without altering their execution status. These may include |
1025 |
< |
* artificially generated or wrapped tasks. This method is designed |
1026 |
< |
* to be invoked only when the pool is known to be |
1025 |
> |
* artificially generated or wrapped tasks. This method is |
1026 |
> |
* designed to be invoked only when the pool is known to be |
1027 |
|
* quiescent. Invocations at other times may not remove all |
1028 |
|
* tasks. A failure encountered while attempting to add elements |
1029 |
|
* to collection {@code c} may result in elements being in |
1120 |
|
} |
1121 |
|
|
1122 |
|
/** |
1123 |
< |
* Attempts to stop all actively executing tasks, and cancels all |
1124 |
< |
* waiting tasks. Tasks that are in the process of being |
1125 |
< |
* submitted or executed concurrently during the course of this |
1126 |
< |
* method may or may not be rejected. Unlike some other executors, |
1127 |
< |
* this method cancels rather than collects non-executed tasks |
1128 |
< |
* upon termination, so always returns an empty list. However, you |
1129 |
< |
* can use method {@link #drainTasksTo} before invoking this |
1130 |
< |
* method to transfer unexecuted tasks to another collection. |
1123 |
> |
* Attempts to cancel and/or stop all tasks, and reject all |
1124 |
> |
* subsequently submitted tasks. Tasks that are in the process of |
1125 |
> |
* being submitted or executed concurrently during the course of |
1126 |
> |
* this method may or may not be rejected. This method cancels |
1127 |
> |
* both existing and unexecuted tasks, in order to permit |
1128 |
> |
* termination in the presence of task dependencies. So the method |
1129 |
> |
* always returns an empty list (unlike the case for some other |
1130 |
> |
* Executors). |
1131 |
|
* |
1132 |
|
* @return an empty list |
1133 |
|
* @throws SecurityException if a security manager exists and |
1152 |
|
|
1153 |
|
/** |
1154 |
|
* Returns {@code true} if the process of termination has |
1155 |
< |
* commenced but possibly not yet completed. |
1155 |
> |
* commenced but not yet completed. This method may be useful for |
1156 |
> |
* debugging. A return of {@code true} reported a sufficient |
1157 |
> |
* period after shutdown may indicate that submitted tasks have |
1158 |
> |
* ignored or suppressed interruption, causing this executor not |
1159 |
> |
* to properly terminate. |
1160 |
|
* |
1161 |
< |
* @return {@code true} if terminating |
1161 |
> |
* @return {@code true} if terminating but not yet terminated |
1162 |
|
*/ |
1163 |
|
public boolean isTerminating() { |
1164 |
< |
return runStateOf(runControl) >= TERMINATING; |
1164 |
> |
return runStateOf(runControl) == TERMINATING; |
1165 |
|
} |
1166 |
|
|
1167 |
|
/** |
1174 |
|
} |
1175 |
|
|
1176 |
|
/** |
1177 |
+ |
* Returns true if pool is not terminating or terminated. |
1178 |
+ |
* Used internally to suppress execution when terminating. |
1179 |
+ |
*/ |
1180 |
+ |
final boolean isProcessingTasks() { |
1181 |
+ |
return runStateOf(runControl) < TERMINATING; |
1182 |
+ |
} |
1183 |
+ |
|
1184 |
+ |
/** |
1185 |
|
* Blocks until all tasks have completed execution after a shutdown |
1186 |
|
* request, or the timeout occurs, or the current thread is |
1187 |
|
* interrupted, whichever happens first. |
1235 |
|
transitionRunStateTo(TERMINATED); |
1236 |
|
termination.signalAll(); |
1237 |
|
} |
1238 |
< |
else if (!isTerminating()) { |
1238 |
> |
else if (isProcessingTasks()) { |
1239 |
|
tryShrinkWorkerArray(); |
1240 |
|
tryResumeSpare(true); // allow replacement |
1241 |
|
} |
1476 |
|
final void sync(ForkJoinWorkerThread w) { |
1477 |
|
updateStealCount(w); // Transfer w's count while it is idle |
1478 |
|
|
1479 |
< |
while (!w.isShutdown() && !isTerminating() && !suspendIfSpare(w)) { |
1479 |
> |
while (!w.isShutdown() && isProcessingTasks() && !suspendIfSpare(w)) { |
1480 |
|
long prev = w.lastEventCount; |
1481 |
|
WaitQueueNode node = null; |
1482 |
|
WaitQueueNode h; |
1681 |
|
for (k = 0; k < len && ws[k] != null; ++k) |
1682 |
|
; |
1683 |
|
} |
1684 |
< |
if (k < len && !isTerminating() && (w = createWorker(k)) != null) { |
1684 |
> |
if (k < len && isProcessingTasks() && (w = createWorker(k)) != null) { |
1685 |
|
ws[k] = w; |
1686 |
|
w.start(); |
1687 |
|
} |
1785 |
|
* Method {@code isReleasable} must return {@code true} if |
1786 |
|
* blocking is not necessary. Method {@code block} blocks the |
1787 |
|
* current thread if necessary (perhaps internally invoking |
1788 |
< |
* {@code isReleasable} before actually blocking.). |
1788 |
> |
* {@code isReleasable} before actually blocking). |
1789 |
|
* |
1790 |
|
* <p>For example, here is a ManagedBlocker based on a |
1791 |
|
* ReentrantLock: |
1824 |
|
|
1825 |
|
/** |
1826 |
|
* Blocks in accord with the given blocker. If the current thread |
1827 |
< |
* is a ForkJoinWorkerThread, this method possibly arranges for a |
1828 |
< |
* spare thread to be activated if necessary to ensure parallelism |
1829 |
< |
* while the current thread is blocked. If |
1830 |
< |
* {@code maintainParallelism} is {@code true} and the pool supports |
1831 |
< |
* it ({@link #getMaintainsParallelism}), this method attempts to |
1832 |
< |
* maintain the pool's nominal parallelism. Otherwise it activates |
1833 |
< |
* a thread only if necessary to avoid complete starvation. This |
1834 |
< |
* option may be preferable when blockages use timeouts, or are |
1835 |
< |
* almost always brief. |
1827 |
> |
* is a {@link ForkJoinWorkerThread}, this method possibly |
1828 |
> |
* arranges for a spare thread to be activated if necessary to |
1829 |
> |
* ensure parallelism while the current thread is blocked. |
1830 |
> |
* |
1831 |
> |
* <p>If {@code maintainParallelism} is {@code true} and the pool |
1832 |
> |
* supports it ({@link #getMaintainsParallelism}), this method |
1833 |
> |
* attempts to maintain the pool's nominal parallelism. Otherwise |
1834 |
> |
* it activates a thread only if necessary to avoid complete |
1835 |
> |
* starvation. This option may be preferable when blockages use |
1836 |
> |
* timeouts, or are almost always brief. |
1837 |
|
* |
1838 |
< |
* <p> If the caller is not a ForkJoinTask, this method is behaviorally |
1839 |
< |
* equivalent to |
1838 |
> |
* <p>If the caller is not a {@link ForkJoinTask}, this method is |
1839 |
> |
* behaviorally equivalent to |
1840 |
|
* <pre> {@code |
1841 |
|
* while (!blocker.isReleasable()) |
1842 |
|
* if (blocker.block()) |
1843 |
|
* return; |
1844 |
|
* }</pre> |
1845 |
< |
* If the caller is a ForkJoinTask, then the pool may first |
1846 |
< |
* be expanded to ensure parallelism, and later adjusted. |
1845 |
> |
* |
1846 |
> |
* If the caller is a {@code ForkJoinTask}, then the pool may |
1847 |
> |
* first be expanded to ensure parallelism, and later adjusted. |
1848 |
|
* |
1849 |
|
* @param blocker the blocker |
1850 |
|
* @param maintainParallelism if {@code true} and supported by |