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