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