5 |
|
*/ |
6 |
|
|
7 |
|
package jsr166y; |
8 |
< |
import java.util.*; |
8 |
> |
|
9 |
|
import java.util.concurrent.*; |
10 |
< |
import java.util.concurrent.locks.*; |
11 |
< |
import java.util.concurrent.atomic.*; |
12 |
< |
import sun.misc.Unsafe; |
13 |
< |
import java.lang.reflect.*; |
10 |
> |
|
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 |
|
|
22 |
|
/** |
23 |
< |
* An {@link ExecutorService} for running {@link ForkJoinTask}s. A |
24 |
< |
* ForkJoinPool provides the entry point for submissions from |
25 |
< |
* non-ForkJoinTasks, as well as management and monitoring operations. |
26 |
< |
* Normally a single ForkJoinPool is used for a large number of |
20 |
< |
* submitted tasks. Otherwise, use would not usually outweigh the |
21 |
< |
* construction and bookkeeping overhead of creating a large set of |
22 |
< |
* threads. |
23 |
> |
* An {@link ExecutorService} for running {@link ForkJoinTask}s. |
24 |
> |
* A {@code ForkJoinPool} provides the entry point for submissions |
25 |
> |
* from non-{@code ForkJoinTask}s, as well as management and |
26 |
> |
* monitoring operations. |
27 |
|
* |
28 |
< |
* <p>ForkJoinPools differ from other kinds of Executors mainly in |
29 |
< |
* that they provide <em>work-stealing</em>: all threads in the pool |
30 |
< |
* attempt to find and execute subtasks created by other active tasks |
31 |
< |
* (eventually blocking if none exist). This makes them efficient when |
32 |
< |
* most tasks spawn other subtasks (as do most ForkJoinTasks), as well |
33 |
< |
* as the mixed execution of some plain Runnable- or Callable- based |
34 |
< |
* activities along with ForkJoinTasks. When setting |
35 |
< |
* {@code setAsyncMode}, a ForkJoinPools may also be appropriate for |
36 |
< |
* use with fine-grained tasks that are never joined. Otherwise, other |
37 |
< |
* ExecutorService implementations are typically more appropriate |
38 |
< |
* choices. |
28 |
> |
* <p>A {@code ForkJoinPool} differs from other kinds of {@link |
29 |
> |
* ExecutorService} mainly by virtue of employing |
30 |
> |
* <em>work-stealing</em>: all threads in the pool attempt to find and |
31 |
> |
* execute subtasks created by other active tasks (eventually blocking |
32 |
> |
* waiting for work if none exist). This enables efficient processing |
33 |
> |
* when most tasks spawn other subtasks (as do most {@code |
34 |
> |
* ForkJoinTask}s). A {@code ForkJoinPool} may also be used for mixed |
35 |
> |
* execution of some plain {@code Runnable}- or {@code Callable}- |
36 |
> |
* based activities along with {@code ForkJoinTask}s. When setting |
37 |
> |
* {@linkplain #setAsyncMode async mode}, a {@code ForkJoinPool} may |
38 |
> |
* also be appropriate for use with fine-grained tasks of any form |
39 |
> |
* that are never joined. Otherwise, other {@code ExecutorService} |
40 |
> |
* implementations are typically more appropriate choices. |
41 |
|
* |
42 |
< |
* <p>A ForkJoinPool may be constructed with a given parallelism level |
43 |
< |
* (target pool size), which it attempts to maintain by dynamically |
44 |
< |
* adding, suspending, or resuming threads, even if some tasks are |
45 |
< |
* waiting to join others. However, no such adjustments are performed |
46 |
< |
* in the face of blocked IO or other unmanaged synchronization. The |
47 |
< |
* nested {@code ManagedBlocker} interface enables extension of |
48 |
< |
* the kinds of synchronization accommodated. The target parallelism |
49 |
< |
* level may also be changed dynamically ({@code setParallelism}) |
50 |
< |
* and thread construction can be limited using methods |
51 |
< |
* {@code setMaximumPoolSize} and/or |
52 |
< |
* {@code setMaintainsParallelism}. |
42 |
> |
* <p>A {@code ForkJoinPool} is constructed with a given target |
43 |
> |
* parallelism level; by default, equal to the number of available |
44 |
> |
* processors. Unless configured otherwise via {@link |
45 |
> |
* #setMaintainsParallelism}, the pool attempts to maintain this |
46 |
> |
* number of active (or available) threads by dynamically adding, |
47 |
> |
* suspending, or resuming internal worker threads, even if some tasks |
48 |
> |
* are stalled waiting to join others. However, no such adjustments |
49 |
> |
* are performed in the face of blocked IO or other unmanaged |
50 |
> |
* synchronization. The nested {@link ManagedBlocker} interface |
51 |
> |
* enables extension of the kinds of synchronization accommodated. |
52 |
> |
* The target parallelism level may also be changed dynamically |
53 |
> |
* ({@link #setParallelism}). The total number of threads may be |
54 |
> |
* limited using method {@link #setMaximumPoolSize}, in which case it |
55 |
> |
* may become possible for the activities of a pool to stall due to |
56 |
> |
* the lack of available threads to process new tasks. |
57 |
|
* |
58 |
|
* <p>In addition to execution and lifecycle control methods, this |
59 |
|
* class provides status check methods (for example |
60 |
< |
* {@code getStealCount}) that are intended to aid in developing, |
60 |
> |
* {@link #getStealCount}) that are intended to aid in developing, |
61 |
|
* tuning, and monitoring fork/join applications. Also, method |
62 |
< |
* {@code toString} returns indications of pool state in a |
62 |
> |
* {@link #toString} returns indications of pool state in a |
63 |
|
* convenient form for informal monitoring. |
64 |
|
* |
65 |
+ |
* <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is |
66 |
+ |
* used for all parallel task execution in a program or subsystem. |
67 |
+ |
* Otherwise, use would not usually outweigh the construction and |
68 |
+ |
* bookkeeping overhead of creating a large set of threads. For |
69 |
+ |
* example, a common pool could be used for the {@code SortTasks} |
70 |
+ |
* illustrated in {@link RecursiveAction}. Because {@code |
71 |
+ |
* ForkJoinPool} uses threads in {@linkplain java.lang.Thread#isDaemon |
72 |
+ |
* daemon} mode, there is typically no need to explicitly {@link |
73 |
+ |
* #shutdown} such a pool upon program exit. |
74 |
+ |
* |
75 |
+ |
* <pre> |
76 |
+ |
* static final ForkJoinPool mainPool = new ForkJoinPool(); |
77 |
+ |
* ... |
78 |
+ |
* public void sort(long[] array) { |
79 |
+ |
* mainPool.invoke(new SortTask(array, 0, array.length)); |
80 |
+ |
* } |
81 |
+ |
* </pre> |
82 |
+ |
* |
83 |
|
* <p><b>Implementation notes</b>: This implementation restricts the |
84 |
|
* maximum number of running threads to 32767. Attempts to create |
85 |
< |
* pools with greater than the maximum result in |
86 |
< |
* IllegalArgumentExceptions. |
85 |
> |
* pools with greater than the maximum number result in |
86 |
> |
* {@code IllegalArgumentException}. |
87 |
> |
* |
88 |
> |
* <p>This implementation rejects submitted tasks (that is, by throwing |
89 |
> |
* {@link RejectedExecutionException}) only when the pool is shut down. |
90 |
> |
* |
91 |
> |
* @since 1.7 |
92 |
> |
* @author Doug Lea |
93 |
|
*/ |
94 |
|
public class ForkJoinPool extends AbstractExecutorService { |
95 |
|
|
105 |
|
private static final int MAX_THREADS = 0x7FFF; |
106 |
|
|
107 |
|
/** |
108 |
< |
* Factory for creating new ForkJoinWorkerThreads. A |
109 |
< |
* ForkJoinWorkerThreadFactory must be defined and used for |
110 |
< |
* ForkJoinWorkerThread subclasses that extend base functionality |
111 |
< |
* or initialize threads with different contexts. |
108 |
> |
* Factory for creating new {@link ForkJoinWorkerThread}s. |
109 |
> |
* A {@code ForkJoinWorkerThreadFactory} must be defined and used |
110 |
> |
* for {@code ForkJoinWorkerThread} subclasses that extend base |
111 |
> |
* functionality or initialize threads with different contexts. |
112 |
|
*/ |
113 |
|
public static interface ForkJoinWorkerThreadFactory { |
114 |
|
/** |
115 |
|
* Returns a new worker thread operating in the given pool. |
116 |
|
* |
117 |
|
* @param pool the pool this thread works in |
118 |
< |
* @throws NullPointerException if pool is null; |
118 |
> |
* @throws NullPointerException if the pool is null |
119 |
|
*/ |
120 |
|
public ForkJoinWorkerThread newThread(ForkJoinPool pool); |
121 |
|
} |
122 |
|
|
123 |
|
/** |
124 |
< |
* Default ForkJoinWorkerThreadFactory implementation, creates a |
124 |
> |
* Default ForkJoinWorkerThreadFactory implementation; creates a |
125 |
|
* new ForkJoinWorkerThread. |
126 |
|
*/ |
127 |
|
static class DefaultForkJoinWorkerThreadFactory |
215 |
|
private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue; |
216 |
|
|
217 |
|
/** |
218 |
< |
* Head of Treiber stack for barrier sync. See below for explanation |
218 |
> |
* Head of Treiber stack for barrier sync. See below for explanation. |
219 |
|
*/ |
220 |
|
private volatile WaitQueueNode syncStack; |
221 |
|
|
250 |
|
* threads, packed into one int to ensure consistent snapshot when |
251 |
|
* making decisions about creating and suspending spare |
252 |
|
* threads. Updated only by CAS. Note: CASes in |
253 |
< |
* updateRunningCount and preJoin running active count is in low |
254 |
< |
* word, so need to be modified if this changes |
253 |
> |
* updateRunningCount and preJoin assume that running active count |
254 |
> |
* is in low word, so need to be modified if this changes. |
255 |
|
*/ |
256 |
|
private volatile int workerCounts; |
257 |
|
|
263 |
|
* Adds delta (which may be negative) to running count. This must |
264 |
|
* be called before (with negative arg) and after (with positive) |
265 |
|
* any managed synchronization (i.e., mainly, joins). |
266 |
+ |
* |
267 |
|
* @param delta the number to add |
268 |
|
*/ |
269 |
|
final void updateRunningCount(int delta) { |
270 |
|
int s; |
271 |
< |
do;while (!casWorkerCounts(s = workerCounts, s + delta)); |
271 |
> |
do {} while (!casWorkerCounts(s = workerCounts, s + delta)); |
272 |
|
} |
273 |
|
|
274 |
|
/** |
275 |
|
* Adds delta (which may be negative) to both total and running |
276 |
|
* count. This must be called upon creation and termination of |
277 |
|
* worker threads. |
278 |
+ |
* |
279 |
|
* @param delta the number to add |
280 |
|
*/ |
281 |
|
private void updateWorkerCount(int delta) { |
282 |
|
int d = delta + (delta << 16); // add to both lo and hi parts |
283 |
|
int s; |
284 |
< |
do;while (!casWorkerCounts(s = workerCounts, s + d)); |
284 |
> |
do {} while (!casWorkerCounts(s = workerCounts, s + d)); |
285 |
|
} |
286 |
|
|
287 |
|
/** |
307 |
|
private static int runControlFor(int r, int a) { return (r << 16) + a; } |
308 |
|
|
309 |
|
/** |
310 |
< |
* Try incrementing active count; fail on contention. Called by |
311 |
< |
* workers before/during executing tasks. |
312 |
< |
* @return true on success; |
310 |
> |
* Tries incrementing active count; fails on contention. |
311 |
> |
* Called by workers before/during executing tasks. |
312 |
> |
* |
313 |
> |
* @return true on success |
314 |
|
*/ |
315 |
|
final boolean tryIncrementActiveCount() { |
316 |
|
int c = runControl; |
321 |
|
* Tries decrementing active count; fails on contention. |
322 |
|
* Possibly triggers termination on success. |
323 |
|
* Called by workers when they can't find tasks. |
324 |
+ |
* |
325 |
|
* @return true on success |
326 |
|
*/ |
327 |
|
final boolean tryDecrementActiveCount() { |
335 |
|
} |
336 |
|
|
337 |
|
/** |
338 |
< |
* Returns true if argument represents zero active count and |
339 |
< |
* nonzero runstate, which is the triggering condition for |
338 |
> |
* Returns {@code true} if argument represents zero active count |
339 |
> |
* and nonzero runstate, which is the triggering condition for |
340 |
|
* terminating on shutdown. |
341 |
|
*/ |
342 |
|
private static boolean canTerminateOnShutdown(int c) { |
343 |
< |
return ((c & -c) >>> 16) != 0; // i.e. least bit is nonzero runState bit |
343 |
> |
// i.e. least bit is nonzero runState bit |
344 |
> |
return ((c & -c) >>> 16) != 0; |
345 |
|
} |
346 |
|
|
347 |
|
/** |
366 |
|
// Constructors |
367 |
|
|
368 |
|
/** |
369 |
< |
* Creates a ForkJoinPool with a pool size equal to the number of |
370 |
< |
* processors available on the system and using the default |
371 |
< |
* ForkJoinWorkerThreadFactory, |
369 |
> |
* Creates a {@code ForkJoinPool} with parallelism equal to {@link |
370 |
> |
* java.lang.Runtime#availableProcessors}, and using the {@linkplain |
371 |
> |
* #defaultForkJoinWorkerThreadFactory default thread factory}. |
372 |
> |
* |
373 |
|
* @throws SecurityException if a security manager exists and |
374 |
|
* the caller is not permitted to modify threads |
375 |
|
* because it does not hold {@link |
376 |
< |
* java.lang.RuntimePermission}{@code ("modifyThread")}, |
376 |
> |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
377 |
|
*/ |
378 |
|
public ForkJoinPool() { |
379 |
|
this(Runtime.getRuntime().availableProcessors(), |
381 |
|
} |
382 |
|
|
383 |
|
/** |
384 |
< |
* Creates a ForkJoinPool with the indicated parallelism level |
385 |
< |
* threads, and using the default ForkJoinWorkerThreadFactory, |
386 |
< |
* @param parallelism the number of worker threads |
384 |
> |
* Creates a {@code ForkJoinPool} with the indicated parallelism |
385 |
> |
* level and using the {@linkplain |
386 |
> |
* #defaultForkJoinWorkerThreadFactory default thread factory}. |
387 |
> |
* |
388 |
> |
* @param parallelism the parallelism level |
389 |
|
* @throws IllegalArgumentException if parallelism less than or |
390 |
< |
* equal to zero |
390 |
> |
* equal to zero, or greater than implementation limit |
391 |
|
* @throws SecurityException if a security manager exists and |
392 |
|
* the caller is not permitted to modify threads |
393 |
|
* because it does not hold {@link |
394 |
< |
* java.lang.RuntimePermission}{@code ("modifyThread")}, |
394 |
> |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
395 |
|
*/ |
396 |
|
public ForkJoinPool(int parallelism) { |
397 |
|
this(parallelism, defaultForkJoinWorkerThreadFactory); |
398 |
|
} |
399 |
|
|
400 |
|
/** |
401 |
< |
* Creates a ForkJoinPool with parallelism equal to the number of |
402 |
< |
* processors available on the system and using the given |
403 |
< |
* ForkJoinWorkerThreadFactory, |
401 |
> |
* Creates a {@code ForkJoinPool} with parallelism equal to {@link |
402 |
> |
* java.lang.Runtime#availableProcessors}, and using the given |
403 |
> |
* thread factory. |
404 |
> |
* |
405 |
|
* @param factory the factory for creating new threads |
406 |
< |
* @throws NullPointerException if factory is null |
406 |
> |
* @throws NullPointerException if the factory is null |
407 |
|
* @throws SecurityException if a security manager exists and |
408 |
|
* the caller is not permitted to modify threads |
409 |
|
* because it does not hold {@link |
410 |
< |
* java.lang.RuntimePermission}{@code ("modifyThread")}, |
410 |
> |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
411 |
|
*/ |
412 |
|
public ForkJoinPool(ForkJoinWorkerThreadFactory factory) { |
413 |
|
this(Runtime.getRuntime().availableProcessors(), factory); |
414 |
|
} |
415 |
|
|
416 |
|
/** |
417 |
< |
* Creates a ForkJoinPool with the given parallelism and factory. |
417 |
> |
* Creates a {@code ForkJoinPool} with the given parallelism and |
418 |
> |
* thread factory. |
419 |
|
* |
420 |
< |
* @param parallelism the targeted number of worker threads |
420 |
> |
* @param parallelism the parallelism level |
421 |
|
* @param factory the factory for creating new threads |
422 |
|
* @throws IllegalArgumentException if parallelism less than or |
423 |
< |
* equal to zero, or greater than implementation limit. |
424 |
< |
* @throws NullPointerException if factory is null |
423 |
> |
* equal to zero, or greater than implementation limit |
424 |
> |
* @throws NullPointerException if the factory is null |
425 |
|
* @throws SecurityException if a security manager exists and |
426 |
|
* the caller is not permitted to modify threads |
427 |
|
* because it does not hold {@link |
428 |
< |
* java.lang.RuntimePermission}{@code ("modifyThread")}, |
428 |
> |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
429 |
|
*/ |
430 |
|
public ForkJoinPool(int parallelism, ForkJoinWorkerThreadFactory factory) { |
431 |
|
if (parallelism <= 0 || parallelism > MAX_THREADS) |
446 |
|
} |
447 |
|
|
448 |
|
/** |
449 |
< |
* Create new worker using factory. |
449 |
> |
* Creates a new worker thread using factory. |
450 |
> |
* |
451 |
|
* @param index the index to assign worker |
452 |
< |
* @return new worker, or null of factory failed |
452 |
> |
* @return new worker, or null if factory failed |
453 |
|
*/ |
454 |
|
private ForkJoinWorkerThread createWorker(int index) { |
455 |
|
Thread.UncaughtExceptionHandler h = ueh; |
469 |
|
* Returns a good size for worker array given pool size. |
470 |
|
* Currently requires size to be a power of two. |
471 |
|
*/ |
472 |
< |
private static int arraySizeFor(int ps) { |
473 |
< |
return ps <= 1? 1 : (1 << (32 - Integer.numberOfLeadingZeros(ps-1))); |
472 |
> |
private static int arraySizeFor(int poolSize) { |
473 |
> |
if (poolSize <= 1) |
474 |
> |
return 1; |
475 |
> |
// See Hackers Delight, sec 3.2 |
476 |
> |
int c = poolSize >= MAX_THREADS ? MAX_THREADS : (poolSize - 1); |
477 |
> |
c |= c >>> 1; |
478 |
> |
c |= c >>> 2; |
479 |
> |
c |= c >>> 4; |
480 |
> |
c |= c >>> 8; |
481 |
> |
c |= c >>> 16; |
482 |
> |
return c + 1; |
483 |
|
} |
484 |
|
|
485 |
|
/** |
486 |
|
* Creates or resizes array if necessary to hold newLength. |
487 |
< |
* Call only under exclusion or lock. |
487 |
> |
* Call only under exclusion. |
488 |
> |
* |
489 |
|
* @return the array |
490 |
|
*/ |
491 |
|
private ForkJoinWorkerThread[] ensureWorkerArrayCapacity(int newLength) { |
499 |
|
} |
500 |
|
|
501 |
|
/** |
502 |
< |
* Try to shrink workers into smaller array after one or more terminate |
502 |
> |
* Tries to shrink workers into smaller array after one or more terminate. |
503 |
|
*/ |
504 |
|
private void tryShrinkWorkerArray() { |
505 |
|
ForkJoinWorkerThread[] ws = workers; |
515 |
|
} |
516 |
|
|
517 |
|
/** |
518 |
< |
* Initialize workers if necessary |
518 |
> |
* Initializes workers if necessary. |
519 |
|
*/ |
520 |
|
final void ensureWorkerInitialization() { |
521 |
|
ForkJoinWorkerThread[] ws = workers; |
526 |
|
ws = workers; |
527 |
|
if (ws == null) { |
528 |
|
int ps = parallelism; |
529 |
+ |
updateWorkerCount(ps); |
530 |
|
ws = ensureWorkerArrayCapacity(ps); |
531 |
|
for (int i = 0; i < ps; ++i) { |
532 |
|
ForkJoinWorkerThread w = createWorker(i); |
533 |
|
if (w != null) { |
534 |
|
ws[i] = w; |
535 |
|
w.start(); |
480 |
– |
updateWorkerCount(1); |
536 |
|
} |
537 |
+ |
else |
538 |
+ |
updateWorkerCount(-1); |
539 |
|
} |
540 |
|
} |
541 |
|
} finally { |
584 |
|
* Common code for execute, invoke and submit |
585 |
|
*/ |
586 |
|
private <T> void doSubmit(ForkJoinTask<T> task) { |
587 |
+ |
if (task == null) |
588 |
+ |
throw new NullPointerException(); |
589 |
|
if (isShutdown()) |
590 |
|
throw new RejectedExecutionException(); |
591 |
|
if (workers == null) |
595 |
|
} |
596 |
|
|
597 |
|
/** |
598 |
< |
* Performs the given task; returning its result upon completion |
598 |
> |
* Performs the given task, returning its result upon completion. |
599 |
> |
* |
600 |
|
* @param task the task |
601 |
|
* @return the task's result |
602 |
< |
* @throws NullPointerException if task is null |
603 |
< |
* @throws RejectedExecutionException if pool is shut down |
602 |
> |
* @throws NullPointerException if the task is null |
603 |
> |
* @throws RejectedExecutionException if the task cannot be |
604 |
> |
* scheduled for execution |
605 |
|
*/ |
606 |
|
public <T> T invoke(ForkJoinTask<T> task) { |
607 |
|
doSubmit(task); |
610 |
|
|
611 |
|
/** |
612 |
|
* Arranges for (asynchronous) execution of the given task. |
613 |
+ |
* |
614 |
|
* @param task the task |
615 |
< |
* @throws NullPointerException if task is null |
616 |
< |
* @throws RejectedExecutionException if pool is shut down |
615 |
> |
* @throws NullPointerException if the task is null |
616 |
> |
* @throws RejectedExecutionException if the task cannot be |
617 |
> |
* scheduled for execution |
618 |
|
*/ |
619 |
< |
public <T> void execute(ForkJoinTask<T> task) { |
619 |
> |
public void execute(ForkJoinTask<?> task) { |
620 |
|
doSubmit(task); |
621 |
|
} |
622 |
|
|
623 |
|
// AbstractExecutorService methods |
624 |
|
|
625 |
+ |
/** |
626 |
+ |
* @throws NullPointerException if the task is null |
627 |
+ |
* @throws RejectedExecutionException if the task cannot be |
628 |
+ |
* scheduled for execution |
629 |
+ |
*/ |
630 |
|
public void execute(Runnable task) { |
631 |
< |
doSubmit(new AdaptedRunnable<Void>(task, null)); |
631 |
> |
ForkJoinTask<?> job; |
632 |
> |
if (task instanceof ForkJoinTask<?>) // avoid re-wrap |
633 |
> |
job = (ForkJoinTask<?>) task; |
634 |
> |
else |
635 |
> |
job = ForkJoinTask.adapt(task, null); |
636 |
> |
doSubmit(job); |
637 |
|
} |
638 |
|
|
639 |
+ |
/** |
640 |
+ |
* @throws NullPointerException if the task is null |
641 |
+ |
* @throws RejectedExecutionException if the task cannot be |
642 |
+ |
* scheduled for execution |
643 |
+ |
*/ |
644 |
|
public <T> ForkJoinTask<T> submit(Callable<T> task) { |
645 |
< |
ForkJoinTask<T> job = new AdaptedCallable<T>(task); |
645 |
> |
ForkJoinTask<T> job = ForkJoinTask.adapt(task); |
646 |
|
doSubmit(job); |
647 |
|
return job; |
648 |
|
} |
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 <T> ForkJoinTask<T> submit(Runnable task, T result) { |
656 |
< |
ForkJoinTask<T> job = new AdaptedRunnable<T>(task, result); |
656 |
> |
ForkJoinTask<T> job = ForkJoinTask.adapt(task, result); |
657 |
|
doSubmit(job); |
658 |
|
return job; |
659 |
|
} |
660 |
|
|
661 |
+ |
/** |
662 |
+ |
* @throws NullPointerException if the task is null |
663 |
+ |
* @throws RejectedExecutionException if the task cannot be |
664 |
+ |
* scheduled for execution |
665 |
+ |
*/ |
666 |
|
public ForkJoinTask<?> submit(Runnable task) { |
667 |
< |
ForkJoinTask<Void> job = new AdaptedRunnable<Void>(task, null); |
667 |
> |
ForkJoinTask<?> job; |
668 |
> |
if (task instanceof ForkJoinTask<?>) // avoid re-wrap |
669 |
> |
job = (ForkJoinTask<?>) task; |
670 |
> |
else |
671 |
> |
job = ForkJoinTask.adapt(task, null); |
672 |
|
doSubmit(job); |
673 |
|
return job; |
674 |
|
} |
675 |
|
|
676 |
|
/** |
677 |
< |
* Adaptor for Runnables. This implements RunnableFuture |
678 |
< |
* to be compliant with AbstractExecutorService constraints |
677 |
> |
* Submits a ForkJoinTask for execution. |
678 |
> |
* |
679 |
> |
* @param task the task to submit |
680 |
> |
* @return the task |
681 |
> |
* @throws NullPointerException if the task is null |
682 |
> |
* @throws RejectedExecutionException if the task cannot be |
683 |
> |
* scheduled for execution |
684 |
|
*/ |
685 |
< |
static final class AdaptedRunnable<T> extends ForkJoinTask<T> |
686 |
< |
implements RunnableFuture<T> { |
687 |
< |
final Runnable runnable; |
591 |
< |
final T resultOnCompletion; |
592 |
< |
T result; |
593 |
< |
AdaptedRunnable(Runnable runnable, T result) { |
594 |
< |
if (runnable == null) throw new NullPointerException(); |
595 |
< |
this.runnable = runnable; |
596 |
< |
this.resultOnCompletion = result; |
597 |
< |
} |
598 |
< |
public T getRawResult() { return result; } |
599 |
< |
public void setRawResult(T v) { result = v; } |
600 |
< |
public boolean exec() { |
601 |
< |
runnable.run(); |
602 |
< |
result = resultOnCompletion; |
603 |
< |
return true; |
604 |
< |
} |
605 |
< |
public void run() { invoke(); } |
685 |
> |
public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) { |
686 |
> |
doSubmit(task); |
687 |
> |
return task; |
688 |
|
} |
689 |
|
|
608 |
– |
/** |
609 |
– |
* Adaptor for Callables |
610 |
– |
*/ |
611 |
– |
static final class AdaptedCallable<T> extends ForkJoinTask<T> |
612 |
– |
implements RunnableFuture<T> { |
613 |
– |
final Callable<T> callable; |
614 |
– |
T result; |
615 |
– |
AdaptedCallable(Callable<T> callable) { |
616 |
– |
if (callable == null) throw new NullPointerException(); |
617 |
– |
this.callable = callable; |
618 |
– |
} |
619 |
– |
public T getRawResult() { return result; } |
620 |
– |
public void setRawResult(T v) { result = v; } |
621 |
– |
public boolean exec() { |
622 |
– |
try { |
623 |
– |
result = callable.call(); |
624 |
– |
return true; |
625 |
– |
} catch (Error err) { |
626 |
– |
throw err; |
627 |
– |
} catch (RuntimeException rex) { |
628 |
– |
throw rex; |
629 |
– |
} catch (Exception ex) { |
630 |
– |
throw new RuntimeException(ex); |
631 |
– |
} |
632 |
– |
} |
633 |
– |
public void run() { invoke(); } |
634 |
– |
} |
690 |
|
|
691 |
+ |
/** |
692 |
+ |
* @throws NullPointerException {@inheritDoc} |
693 |
+ |
* @throws RejectedExecutionException {@inheritDoc} |
694 |
+ |
*/ |
695 |
|
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) { |
696 |
< |
ArrayList<ForkJoinTask<T>> ts = |
696 |
> |
ArrayList<ForkJoinTask<T>> forkJoinTasks = |
697 |
|
new ArrayList<ForkJoinTask<T>>(tasks.size()); |
698 |
< |
for (Callable<T> c : tasks) |
699 |
< |
ts.add(new AdaptedCallable<T>(c)); |
700 |
< |
invoke(new InvokeAll<T>(ts)); |
701 |
< |
return (List<Future<T>>)(List)ts; |
698 |
> |
for (Callable<T> task : tasks) |
699 |
> |
forkJoinTasks.add(ForkJoinTask.adapt(task)); |
700 |
> |
invoke(new InvokeAll<T>(forkJoinTasks)); |
701 |
> |
|
702 |
> |
@SuppressWarnings({"unchecked", "rawtypes"}) |
703 |
> |
List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks; |
704 |
> |
return futures; |
705 |
|
} |
706 |
|
|
707 |
|
static final class InvokeAll<T> extends RecursiveAction { |
708 |
|
final ArrayList<ForkJoinTask<T>> tasks; |
709 |
|
InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; } |
710 |
|
public void compute() { |
711 |
< |
try { invokeAll(tasks); } catch(Exception ignore) {} |
711 |
> |
try { invokeAll(tasks); } |
712 |
> |
catch (Exception ignore) {} |
713 |
|
} |
714 |
+ |
private static final long serialVersionUID = -7914297376763021607L; |
715 |
|
} |
716 |
|
|
717 |
|
// Configuration and status settings and queries |
718 |
|
|
719 |
|
/** |
720 |
< |
* Returns the factory used for constructing new workers |
720 |
> |
* Returns the factory used for constructing new workers. |
721 |
|
* |
722 |
|
* @return the factory used for constructing new workers |
723 |
|
*/ |
728 |
|
/** |
729 |
|
* Returns the handler for internal worker threads that terminate |
730 |
|
* due to unrecoverable errors encountered while executing tasks. |
731 |
< |
* @return the handler, or null if none |
731 |
> |
* |
732 |
> |
* @return the handler, or {@code null} if none |
733 |
|
*/ |
734 |
|
public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() { |
735 |
|
Thread.UncaughtExceptionHandler h; |
750 |
|
* as handler. |
751 |
|
* |
752 |
|
* @param h the new handler |
753 |
< |
* @return the old handler, or null if none |
753 |
> |
* @return the old handler, or {@code null} if none |
754 |
|
* @throws SecurityException if a security manager exists and |
755 |
|
* the caller is not permitted to modify threads |
756 |
|
* because it does not hold {@link |
757 |
< |
* java.lang.RuntimePermission}{@code ("modifyThread")}, |
757 |
> |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
758 |
|
*/ |
759 |
|
public Thread.UncaughtExceptionHandler |
760 |
|
setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h) { |
782 |
|
|
783 |
|
/** |
784 |
|
* Sets the target parallelism level of this pool. |
785 |
+ |
* |
786 |
|
* @param parallelism the target parallelism |
787 |
|
* @throws IllegalArgumentException if parallelism less than or |
788 |
< |
* equal to zero or greater than maximum size bounds. |
788 |
> |
* equal to zero or greater than maximum size bounds |
789 |
|
* @throws SecurityException if a security manager exists and |
790 |
|
* the caller is not permitted to modify threads |
791 |
|
* because it does not hold {@link |
792 |
< |
* java.lang.RuntimePermission}{@code ("modifyThread")}, |
792 |
> |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
793 |
|
*/ |
794 |
|
public void setParallelism(int parallelism) { |
795 |
|
checkPermission(); |
798 |
|
final ReentrantLock lock = this.workerLock; |
799 |
|
lock.lock(); |
800 |
|
try { |
801 |
< |
if (!isTerminating()) { |
801 |
> |
if (isProcessingTasks()) { |
802 |
|
int p = this.parallelism; |
803 |
|
this.parallelism = parallelism; |
804 |
< |
if (parallelism > p) |
805 |
< |
createAndStartAddedWorkers(); |
806 |
< |
else |
807 |
< |
trimSpares(); |
804 |
> |
if (workers != null) { |
805 |
> |
if (parallelism > p) |
806 |
> |
createAndStartAddedWorkers(); |
807 |
> |
else |
808 |
> |
trimSpares(); |
809 |
> |
} |
810 |
|
} |
811 |
|
} finally { |
812 |
|
lock.unlock(); |
815 |
|
} |
816 |
|
|
817 |
|
/** |
818 |
< |
* Returns the targeted number of worker threads in this pool. |
818 |
> |
* Returns the targeted parallelism level of this pool. |
819 |
|
* |
820 |
< |
* @return the targeted number of worker threads in this pool |
820 |
> |
* @return the targeted parallelism level of this pool |
821 |
|
*/ |
822 |
|
public int getParallelism() { |
823 |
|
return parallelism; |
826 |
|
/** |
827 |
|
* Returns the number of worker threads that have started but not |
828 |
|
* yet terminated. This result returned by this method may differ |
829 |
< |
* from {@code getParallelism} when threads are created to |
829 |
> |
* from {@link #getParallelism} when threads are created to |
830 |
|
* maintain parallelism when others are cooperatively blocked. |
831 |
|
* |
832 |
|
* @return the number of worker threads |
837 |
|
|
838 |
|
/** |
839 |
|
* Returns the maximum number of threads allowed to exist in the |
840 |
< |
* pool, even if there are insufficient unblocked running threads. |
840 |
> |
* pool. Unless set using {@link #setMaximumPoolSize}, the |
841 |
> |
* maximum is an implementation-defined value designed only to |
842 |
> |
* prevent runaway growth. |
843 |
> |
* |
844 |
|
* @return the maximum |
845 |
|
*/ |
846 |
|
public int getMaximumPoolSize() { |
849 |
|
|
850 |
|
/** |
851 |
|
* Sets the maximum number of threads allowed to exist in the |
852 |
< |
* pool, even if there are insufficient unblocked running threads. |
853 |
< |
* Setting this value has no effect on current pool size. It |
854 |
< |
* controls construction of new threads. |
855 |
< |
* @throws IllegalArgumentException if negative or greater then |
856 |
< |
* internal implementation limit. |
852 |
> |
* pool. The given value should normally be greater than or equal |
853 |
> |
* to the {@link #getParallelism parallelism} level. Setting this |
854 |
> |
* value has no effect on current pool size. It controls |
855 |
> |
* construction of new threads. |
856 |
> |
* |
857 |
> |
* @throws IllegalArgumentException if negative or greater than |
858 |
> |
* internal implementation limit |
859 |
|
*/ |
860 |
|
public void setMaximumPoolSize(int newMax) { |
861 |
|
if (newMax < 0 || newMax > MAX_THREADS) |
865 |
|
|
866 |
|
|
867 |
|
/** |
868 |
< |
* Returns true if this pool dynamically maintains its target |
869 |
< |
* parallelism level. If false, new threads are added only to |
870 |
< |
* avoid possible starvation. |
871 |
< |
* This setting is by default true; |
872 |
< |
* @return true if maintains parallelism |
868 |
> |
* Returns {@code true} if this pool dynamically maintains its |
869 |
> |
* target parallelism level. If false, new threads are added only |
870 |
> |
* to avoid possible starvation. This setting is by default true. |
871 |
> |
* |
872 |
> |
* @return {@code true} if maintains parallelism |
873 |
|
*/ |
874 |
|
public boolean getMaintainsParallelism() { |
875 |
|
return maintainsParallelism; |
879 |
|
* Sets whether this pool dynamically maintains its target |
880 |
|
* parallelism level. If false, new threads are added only to |
881 |
|
* avoid possible starvation. |
882 |
< |
* @param enable true to maintains parallelism |
882 |
> |
* |
883 |
> |
* @param enable {@code true} to maintain parallelism |
884 |
|
*/ |
885 |
|
public void setMaintainsParallelism(boolean enable) { |
886 |
|
maintainsParallelism = enable; |
891 |
|
* tasks that are never joined. This mode may be more appropriate |
892 |
|
* than default locally stack-based mode in applications in which |
893 |
|
* worker threads only process asynchronous tasks. This method is |
894 |
< |
* designed to be invoked only when pool is quiescent, and |
894 |
> |
* designed to be invoked only when the pool is quiescent, and |
895 |
|
* typically only before any tasks are submitted. The effects of |
896 |
|
* invocations at other times may be unpredictable. |
897 |
|
* |
898 |
< |
* @param async if true, use locally FIFO scheduling |
899 |
< |
* @return the previous mode. |
898 |
> |
* @param async if {@code true}, use locally FIFO scheduling |
899 |
> |
* @return the previous mode |
900 |
> |
* @see #getAsyncMode |
901 |
|
*/ |
902 |
|
public boolean setAsyncMode(boolean async) { |
903 |
|
boolean oldMode = locallyFifo; |
914 |
|
} |
915 |
|
|
916 |
|
/** |
917 |
< |
* Returns true if this pool uses local first-in-first-out |
917 |
> |
* Returns {@code true} if this pool uses local first-in-first-out |
918 |
|
* scheduling mode for forked tasks that are never joined. |
919 |
|
* |
920 |
< |
* @return true if this pool uses async mode. |
920 |
> |
* @return {@code true} if this pool uses async mode |
921 |
> |
* @see #setAsyncMode |
922 |
|
*/ |
923 |
|
public boolean getAsyncMode() { |
924 |
|
return locallyFifo; |
939 |
|
* Returns an estimate of the number of threads that are currently |
940 |
|
* stealing or executing tasks. This method may overestimate the |
941 |
|
* number of active threads. |
942 |
< |
* @return the number of active threads. |
942 |
> |
* |
943 |
> |
* @return the number of active threads |
944 |
|
*/ |
945 |
|
public int getActiveThreadCount() { |
946 |
|
return activeCountOf(runControl); |
950 |
|
* Returns an estimate of the number of threads that are currently |
951 |
|
* idle waiting for tasks. This method may underestimate the |
952 |
|
* number of idle threads. |
953 |
< |
* @return the number of idle threads. |
953 |
> |
* |
954 |
> |
* @return the number of idle threads |
955 |
|
*/ |
956 |
|
final int getIdleThreadCount() { |
957 |
|
int c = runningCountOf(workerCounts) - activeCountOf(runControl); |
958 |
< |
return (c <= 0)? 0 : c; |
958 |
> |
return (c <= 0) ? 0 : c; |
959 |
|
} |
960 |
|
|
961 |
|
/** |
962 |
< |
* Returns true if all worker threads are currently idle. An idle |
963 |
< |
* worker is one that cannot obtain a task to execute because none |
964 |
< |
* are available to steal from other threads, and there are no |
965 |
< |
* pending submissions to the pool. This method is conservative: |
966 |
< |
* It might not return true immediately upon idleness of all |
967 |
< |
* threads, but will eventually become true if threads remain |
968 |
< |
* inactive. |
969 |
< |
* @return true if all threads are currently idle |
962 |
> |
* Returns {@code true} if all worker threads are currently idle. |
963 |
> |
* An idle worker is one that cannot obtain a task to execute |
964 |
> |
* because none are available to steal from other threads, and |
965 |
> |
* there are no pending submissions to the pool. This method is |
966 |
> |
* conservative; it might not return {@code true} immediately upon |
967 |
> |
* idleness of all threads, but will eventually become true if |
968 |
> |
* threads remain inactive. |
969 |
> |
* |
970 |
> |
* @return {@code true} if all threads are currently idle |
971 |
|
*/ |
972 |
|
public boolean isQuiescent() { |
973 |
|
return activeCountOf(runControl) == 0; |
978 |
|
* one thread's work queue by another. The reported value |
979 |
|
* underestimates the actual total number of steals when the pool |
980 |
|
* is not quiescent. This value may be useful for monitoring and |
981 |
< |
* tuning fork/join programs: In general, steal counts should be |
981 |
> |
* tuning fork/join programs: in general, steal counts should be |
982 |
|
* high enough to keep threads busy, but low enough to avoid |
983 |
|
* overhead and contention across threads. |
984 |
< |
* @return the number of steals. |
984 |
> |
* |
985 |
> |
* @return the number of steals |
986 |
|
*/ |
987 |
|
public long getStealCount() { |
988 |
|
return stealCount.get(); |
989 |
|
} |
990 |
|
|
991 |
|
/** |
992 |
< |
* Accumulate steal count from a worker. Call only |
993 |
< |
* when worker known to be idle. |
992 |
> |
* Accumulates steal count from a worker. |
993 |
> |
* Call only when worker known to be idle. |
994 |
|
*/ |
995 |
|
private void updateStealCount(ForkJoinWorkerThread w) { |
996 |
|
int sc = w.getAndClearStealCount(); |
1005 |
|
* an approximation, obtained by iterating across all threads in |
1006 |
|
* the pool. This method may be useful for tuning task |
1007 |
|
* granularities. |
1008 |
< |
* @return the number of queued tasks. |
1008 |
> |
* |
1009 |
> |
* @return the number of queued tasks |
1010 |
|
*/ |
1011 |
|
public long getQueuedTaskCount() { |
1012 |
|
long count = 0; |
1022 |
|
} |
1023 |
|
|
1024 |
|
/** |
1025 |
< |
* Returns an estimate of the number tasks submitted to this pool |
1026 |
< |
* that have not yet begun executing. This method takes time |
1025 |
> |
* Returns an estimate of the number of tasks submitted to this |
1026 |
> |
* pool that have not yet begun executing. This method takes time |
1027 |
|
* proportional to the number of submissions. |
1028 |
< |
* @return the number of queued submissions. |
1028 |
> |
* |
1029 |
> |
* @return the number of queued submissions |
1030 |
|
*/ |
1031 |
|
public int getQueuedSubmissionCount() { |
1032 |
|
return submissionQueue.size(); |
1033 |
|
} |
1034 |
|
|
1035 |
|
/** |
1036 |
< |
* Returns true if there are any tasks submitted to this pool |
1037 |
< |
* that have not yet begun executing. |
1038 |
< |
* @return {@code true} if there are any queued submissions. |
1036 |
> |
* Returns {@code true} if there are any tasks submitted to this |
1037 |
> |
* pool that have not yet begun executing. |
1038 |
> |
* |
1039 |
> |
* @return {@code true} if there are any queued submissions |
1040 |
|
*/ |
1041 |
|
public boolean hasQueuedSubmissions() { |
1042 |
|
return !submissionQueue.isEmpty(); |
1046 |
|
* Removes and returns the next unexecuted submission if one is |
1047 |
|
* available. This method may be useful in extensions to this |
1048 |
|
* class that re-assign work in systems with multiple pools. |
1049 |
< |
* @return the next submission, or null if none |
1049 |
> |
* |
1050 |
> |
* @return the next submission, or {@code null} if none |
1051 |
|
*/ |
1052 |
|
protected ForkJoinTask<?> pollSubmission() { |
1053 |
|
return submissionQueue.poll(); |
1057 |
|
* Removes all available unexecuted submitted and forked tasks |
1058 |
|
* from scheduling queues and adds them to the given collection, |
1059 |
|
* without altering their execution status. These may include |
1060 |
< |
* artificially generated or wrapped tasks. This method is designed |
1061 |
< |
* to be invoked only when the pool is known to be |
1060 |
> |
* artificially generated or wrapped tasks. This method is |
1061 |
> |
* designed to be invoked only when the pool is known to be |
1062 |
|
* quiescent. Invocations at other times may not remove all |
1063 |
|
* tasks. A failure encountered while attempting to add elements |
1064 |
|
* to collection {@code c} may result in elements being in |
1066 |
|
* exception is thrown. The behavior of this operation is |
1067 |
|
* undefined if the specified collection is modified while the |
1068 |
|
* operation is in progress. |
1069 |
+ |
* |
1070 |
|
* @param c the collection to transfer elements into |
1071 |
|
* @return the number of elements transferred |
1072 |
|
*/ |
1073 |
< |
protected int drainTasksTo(Collection<ForkJoinTask<?>> c) { |
1073 |
> |
protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) { |
1074 |
|
int n = submissionQueue.drainTo(c); |
1075 |
|
ForkJoinWorkerThread[] ws = workers; |
1076 |
|
if (ws != null) { |
1110 |
|
} |
1111 |
|
|
1112 |
|
private static String runStateToString(int rs) { |
1113 |
< |
switch(rs) { |
1113 |
> |
switch (rs) { |
1114 |
|
case RUNNING: return "Running"; |
1115 |
|
case SHUTDOWN: return "Shutting down"; |
1116 |
|
case TERMINATING: return "Terminating"; |
1127 |
|
* Invocation has no additional effect if already shut down. |
1128 |
|
* Tasks that are in the process of being submitted concurrently |
1129 |
|
* during the course of this method may or may not be rejected. |
1130 |
+ |
* |
1131 |
|
* @throws SecurityException if a security manager exists and |
1132 |
|
* the caller is not permitted to modify threads |
1133 |
|
* because it does not hold {@link |
1134 |
< |
* java.lang.RuntimePermission}{@code ("modifyThread")}, |
1134 |
> |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
1135 |
|
*/ |
1136 |
|
public void shutdown() { |
1137 |
|
checkPermission(); |
1138 |
|
transitionRunStateTo(SHUTDOWN); |
1139 |
< |
if (canTerminateOnShutdown(runControl)) |
1139 |
> |
if (canTerminateOnShutdown(runControl)) { |
1140 |
> |
if (workers == null) { // shutting down before workers created |
1141 |
> |
final ReentrantLock lock = this.workerLock; |
1142 |
> |
lock.lock(); |
1143 |
> |
try { |
1144 |
> |
if (workers == null) { |
1145 |
> |
terminate(); |
1146 |
> |
transitionRunStateTo(TERMINATED); |
1147 |
> |
termination.signalAll(); |
1148 |
> |
} |
1149 |
> |
} finally { |
1150 |
> |
lock.unlock(); |
1151 |
> |
} |
1152 |
> |
} |
1153 |
|
terminateOnShutdown(); |
1154 |
+ |
} |
1155 |
|
} |
1156 |
|
|
1157 |
|
/** |
1158 |
< |
* Attempts to stop all actively executing tasks, and cancels all |
1159 |
< |
* waiting tasks. Tasks that are in the process of being |
1160 |
< |
* submitted or executed concurrently during the course of this |
1161 |
< |
* method may or may not be rejected. Unlike some other executors, |
1162 |
< |
* this method cancels rather than collects non-executed tasks |
1163 |
< |
* upon termination, so always returns an empty list. However, you |
1164 |
< |
* can use method {@code drainTasksTo} before invoking this |
1165 |
< |
* method to transfer unexecuted tasks to another collection. |
1158 |
> |
* Attempts to cancel and/or stop all tasks, and reject all |
1159 |
> |
* subsequently submitted tasks. Tasks that are in the process of |
1160 |
> |
* being submitted or executed concurrently during the course of |
1161 |
> |
* this method may or may not be rejected. This method cancels |
1162 |
> |
* both existing and unexecuted tasks, in order to permit |
1163 |
> |
* termination in the presence of task dependencies. So the method |
1164 |
> |
* always returns an empty list (unlike the case for some other |
1165 |
> |
* Executors). |
1166 |
> |
* |
1167 |
|
* @return an empty list |
1168 |
|
* @throws SecurityException if a security manager exists and |
1169 |
|
* the caller is not permitted to modify threads |
1170 |
|
* because it does not hold {@link |
1171 |
< |
* java.lang.RuntimePermission}{@code ("modifyThread")}, |
1171 |
> |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
1172 |
|
*/ |
1173 |
|
public List<Runnable> shutdownNow() { |
1174 |
|
checkPermission(); |
1187 |
|
|
1188 |
|
/** |
1189 |
|
* Returns {@code true} if the process of termination has |
1190 |
< |
* commenced but possibly not yet completed. |
1190 |
> |
* commenced but not yet completed. This method may be useful for |
1191 |
> |
* debugging. A return of {@code true} reported a sufficient |
1192 |
> |
* period after shutdown may indicate that submitted tasks have |
1193 |
> |
* ignored or suppressed interruption, causing this executor not |
1194 |
> |
* to properly terminate. |
1195 |
|
* |
1196 |
< |
* @return {@code true} if terminating |
1196 |
> |
* @return {@code true} if terminating but not yet terminated |
1197 |
|
*/ |
1198 |
|
public boolean isTerminating() { |
1199 |
< |
return runStateOf(runControl) >= TERMINATING; |
1199 |
> |
return runStateOf(runControl) == TERMINATING; |
1200 |
|
} |
1201 |
|
|
1202 |
|
/** |
1209 |
|
} |
1210 |
|
|
1211 |
|
/** |
1212 |
+ |
* Returns true if pool is not terminating or terminated. |
1213 |
+ |
* Used internally to suppress execution when terminating. |
1214 |
+ |
*/ |
1215 |
+ |
final boolean isProcessingTasks() { |
1216 |
+ |
return runStateOf(runControl) < TERMINATING; |
1217 |
+ |
} |
1218 |
+ |
|
1219 |
+ |
/** |
1220 |
|
* Blocks until all tasks have completed execution after a shutdown |
1221 |
|
* request, or the timeout occurs, or the current thread is |
1222 |
|
* interrupted, whichever happens first. |
1248 |
|
// Shutdown and termination support |
1249 |
|
|
1250 |
|
/** |
1251 |
< |
* Callback from terminating worker. Null out the corresponding |
1252 |
< |
* workers slot, and if terminating, try to terminate, else try to |
1253 |
< |
* shrink workers array. |
1251 |
> |
* Callback from terminating worker. Nulls out the corresponding |
1252 |
> |
* workers slot, and if terminating, tries to terminate; else |
1253 |
> |
* tries to shrink workers array. |
1254 |
> |
* |
1255 |
|
* @param w the worker |
1256 |
|
*/ |
1257 |
|
final void workerTerminated(ForkJoinWorkerThread w) { |
1270 |
|
transitionRunStateTo(TERMINATED); |
1271 |
|
termination.signalAll(); |
1272 |
|
} |
1273 |
< |
else if (!isTerminating()) { |
1273 |
> |
else if (isProcessingTasks()) { |
1274 |
|
tryShrinkWorkerArray(); |
1275 |
|
tryResumeSpare(true); // allow replacement |
1276 |
|
} |
1282 |
|
} |
1283 |
|
|
1284 |
|
/** |
1285 |
< |
* Initiate termination. |
1285 |
> |
* Initiates termination. |
1286 |
|
*/ |
1287 |
|
private void terminate() { |
1288 |
|
if (transitionRunStateTo(TERMINATING)) { |
1380 |
|
} |
1381 |
|
} |
1382 |
|
|
1269 |
– |
|
1383 |
|
/* |
1384 |
|
* Nodes for event barrier to manage idle threads. Queue nodes |
1385 |
|
* are basic Treiber stack nodes, also used for spare stack. |
1403 |
|
* handling: Method signalWork returns without advancing count if |
1404 |
|
* the queue appears to be empty. This would ordinarily result in |
1405 |
|
* races causing some queued waiters not to be woken up. To avoid |
1406 |
< |
* this, the first worker enqueued in method sync (see |
1407 |
< |
* syncIsReleasable) rescans for tasks after being enqueued, and |
1408 |
< |
* helps signal if any are found. This works well because the |
1409 |
< |
* worker has nothing better to do, and so might as well help |
1410 |
< |
* alleviate the overhead and contention on the threads actually |
1411 |
< |
* doing work. Also, since event counts increments on task |
1412 |
< |
* availability exist to maintain liveness (rather than to force |
1413 |
< |
* refreshes etc), it is OK for callers to exit early if |
1301 |
< |
* contending with another signaller. |
1406 |
> |
* this, the first worker enqueued in method sync rescans for |
1407 |
> |
* tasks after being enqueued, and helps signal if any are |
1408 |
> |
* found. This works well because the worker has nothing better to |
1409 |
> |
* do, and so might as well help alleviate the overhead and |
1410 |
> |
* contention on the threads actually doing work. Also, since |
1411 |
> |
* event counts increments on task availability exist to maintain |
1412 |
> |
* liveness (rather than to force refreshes etc), it is OK for |
1413 |
> |
* callers to exit early if contending with another signaller. |
1414 |
|
*/ |
1415 |
|
static final class WaitQueueNode { |
1416 |
|
WaitQueueNode next; // only written before enqueued |
1423 |
|
} |
1424 |
|
|
1425 |
|
/** |
1426 |
< |
* Wakes up waiter, returning false if known to already |
1426 |
> |
* Wakes up waiter, also clearing thread field |
1427 |
|
*/ |
1428 |
< |
boolean signal() { |
1428 |
> |
void signal() { |
1429 |
|
ForkJoinWorkerThread t = thread; |
1430 |
< |
if (t == null) |
1431 |
< |
return false; |
1432 |
< |
thread = null; |
1321 |
< |
LockSupport.unpark(t); |
1322 |
< |
return true; |
1323 |
< |
} |
1324 |
< |
|
1325 |
< |
/** |
1326 |
< |
* Awaits release on sync. |
1327 |
< |
*/ |
1328 |
< |
void awaitSyncRelease(ForkJoinPool p) { |
1329 |
< |
while (thread != null && !p.syncIsReleasable(this)) |
1330 |
< |
LockSupport.park(this); |
1331 |
< |
} |
1332 |
< |
|
1333 |
< |
/** |
1334 |
< |
* Awaits resumption as spare. |
1335 |
< |
*/ |
1336 |
< |
void awaitSpareRelease() { |
1337 |
< |
while (thread != null) { |
1338 |
< |
if (!Thread.interrupted()) |
1339 |
< |
LockSupport.park(this); |
1430 |
> |
if (t != null) { |
1431 |
> |
thread = null; |
1432 |
> |
LockSupport.unpark(t); |
1433 |
|
} |
1434 |
|
} |
1435 |
|
} |
1438 |
|
* Ensures that no thread is waiting for count to advance from the |
1439 |
|
* current value of eventCount read on entry to this method, by |
1440 |
|
* releasing waiting threads if necessary. |
1348 |
– |
* @return the count |
1441 |
|
*/ |
1442 |
< |
final long ensureSync() { |
1442 |
> |
final void ensureSync() { |
1443 |
|
long c = eventCount; |
1444 |
|
WaitQueueNode q; |
1445 |
|
while ((q = syncStack) != null && q.count < c) { |
1450 |
|
break; |
1451 |
|
} |
1452 |
|
} |
1361 |
– |
return c; |
1453 |
|
} |
1454 |
|
|
1455 |
|
/** |
1457 |
|
*/ |
1458 |
|
private void signalIdleWorkers() { |
1459 |
|
long c; |
1460 |
< |
do;while (!casEventCount(c = eventCount, c+1)); |
1460 |
> |
do {} while (!casEventCount(c = eventCount, c+1)); |
1461 |
|
ensureSync(); |
1462 |
|
} |
1463 |
|
|
1464 |
|
/** |
1465 |
|
* Signals threads waiting to poll a task. Because method sync |
1466 |
|
* rechecks availability, it is OK to only proceed if queue |
1467 |
< |
* appears to be non-empty, and OK to skip under contention to |
1468 |
< |
* increment count (since some other thread succeeded). |
1467 |
> |
* appears to be non-empty, and OK if CAS to increment count |
1468 |
> |
* fails (since some other thread succeeded). |
1469 |
|
*/ |
1470 |
|
final void signalWork() { |
1471 |
< |
long c; |
1472 |
< |
WaitQueueNode q; |
1473 |
< |
if (syncStack != null && |
1474 |
< |
casEventCount(c = eventCount, c+1) && |
1475 |
< |
(((q = syncStack) != null && q.count <= c) && |
1476 |
< |
(!casBarrierStack(q, q.next) || !q.signal()))) |
1477 |
< |
ensureSync(); |
1471 |
> |
if (syncStack != null) { |
1472 |
> |
long c = eventCount; |
1473 |
> |
casEventCount(c, c+1); |
1474 |
> |
WaitQueueNode q = syncStack; |
1475 |
> |
if (q != null && q.count <= c) { |
1476 |
> |
if (casBarrierStack(q, q.next)) |
1477 |
> |
q.signal(); |
1478 |
> |
else |
1479 |
> |
ensureSync(); // awaken all on contention |
1480 |
> |
} |
1481 |
> |
} |
1482 |
|
} |
1483 |
|
|
1484 |
|
/** |
1485 |
< |
* Waits until event count advances from last value held by |
1486 |
< |
* caller, or if excess threads, caller is resumed as spare, or |
1485 |
> |
* Possibly blocks until event count advances from last value held |
1486 |
> |
* by caller, or if excess threads, caller is resumed as spare, or |
1487 |
|
* caller or pool is terminating. Updates caller's event on exit. |
1488 |
+ |
* |
1489 |
|
* @param w the calling worker thread |
1490 |
|
*/ |
1491 |
|
final void sync(ForkJoinWorkerThread w) { |
1492 |
|
updateStealCount(w); // Transfer w's count while it is idle |
1493 |
|
|
1494 |
< |
while (!w.isShutdown() && !isTerminating() && !suspendIfSpare(w)) { |
1494 |
> |
if (!w.isShutdown() && isProcessingTasks() && !suspendIfSpare(w)) { |
1495 |
|
long prev = w.lastEventCount; |
1496 |
|
WaitQueueNode node = null; |
1497 |
|
WaitQueueNode h; |
1498 |
< |
while (eventCount == prev && |
1498 |
> |
long c; |
1499 |
> |
while ((c = eventCount) == prev && |
1500 |
|
((h = syncStack) == null || h.count == prev)) { |
1501 |
|
if (node == null) |
1502 |
|
node = new WaitQueueNode(prev, w); |
1503 |
|
if (casBarrierStack(node.next = h, node)) { |
1504 |
< |
node.awaitSyncRelease(this); |
1504 |
> |
if (!Thread.interrupted() && |
1505 |
> |
node.thread != null && |
1506 |
> |
eventCount == prev && |
1507 |
> |
(h != null || // cover signalWork race |
1508 |
> |
(!ForkJoinWorkerThread.hasQueuedTasks(workers) && |
1509 |
> |
eventCount == prev))) |
1510 |
> |
LockSupport.park(this); |
1511 |
> |
c = eventCount; |
1512 |
> |
if (node.thread != null) { // help signal if not unparked |
1513 |
> |
node.thread = null; |
1514 |
> |
if (c == prev) |
1515 |
> |
casEventCount(prev, prev + 1); |
1516 |
> |
} |
1517 |
|
break; |
1518 |
|
} |
1519 |
|
} |
1520 |
< |
long ec = ensureSync(); |
1521 |
< |
if (ec != prev) { |
1413 |
< |
w.lastEventCount = ec; |
1414 |
< |
break; |
1415 |
< |
} |
1416 |
< |
} |
1417 |
< |
} |
1418 |
< |
|
1419 |
< |
/** |
1420 |
< |
* Returns true if worker waiting on sync can proceed: |
1421 |
< |
* - on signal (thread == null) |
1422 |
< |
* - on event count advance (winning race to notify vs signaller) |
1423 |
< |
* - on Interrupt |
1424 |
< |
* - if the first queued node, we find work available |
1425 |
< |
* If node was not signalled and event count not advanced on exit, |
1426 |
< |
* then we also help advance event count. |
1427 |
< |
* @return true if node can be released |
1428 |
< |
*/ |
1429 |
< |
final boolean syncIsReleasable(WaitQueueNode node) { |
1430 |
< |
long prev = node.count; |
1431 |
< |
if (!Thread.interrupted() && node.thread != null && |
1432 |
< |
(node.next != null || |
1433 |
< |
!ForkJoinWorkerThread.hasQueuedTasks(workers)) && |
1434 |
< |
eventCount == prev) |
1435 |
< |
return false; |
1436 |
< |
if (node.thread != null) { |
1437 |
< |
node.thread = null; |
1438 |
< |
long ec = eventCount; |
1439 |
< |
if (prev <= ec) // help signal |
1440 |
< |
casEventCount(ec, ec+1); |
1520 |
> |
w.lastEventCount = c; |
1521 |
> |
ensureSync(); |
1522 |
|
} |
1442 |
– |
return true; |
1523 |
|
} |
1524 |
|
|
1525 |
|
/** |
1526 |
< |
* Returns true if a new sync event occurred since last call to |
1527 |
< |
* sync or this method, if so, updating caller's count. |
1526 |
> |
* Returns {@code true} if a new sync event occurred since last |
1527 |
> |
* call to sync or this method, if so, updating caller's count. |
1528 |
|
*/ |
1529 |
|
final boolean hasNewSyncEvent(ForkJoinWorkerThread w) { |
1530 |
< |
long lc = w.lastEventCount; |
1531 |
< |
long ec = ensureSync(); |
1532 |
< |
if (ec == lc) |
1533 |
< |
return false; |
1534 |
< |
w.lastEventCount = ec; |
1535 |
< |
return true; |
1530 |
> |
long wc = w.lastEventCount; |
1531 |
> |
long c = eventCount; |
1532 |
> |
if (wc != c) |
1533 |
> |
w.lastEventCount = c; |
1534 |
> |
ensureSync(); |
1535 |
> |
return wc != c || wc != eventCount; |
1536 |
|
} |
1537 |
|
|
1538 |
|
// Parallelism maintenance |
1544 |
|
* spare thread when one is about to block (and remove or |
1545 |
|
* suspend it later when unblocked -- see suspendIfSpare). |
1546 |
|
* However, implementing this idea requires coping with |
1547 |
< |
* several problems: We have imperfect information about the |
1547 |
> |
* several problems: we have imperfect information about the |
1548 |
|
* states of threads. Some count updates can and usually do |
1549 |
|
* lag run state changes, despite arrangements to keep them |
1550 |
|
* accurate (for example, when possible, updating counts |
1567 |
|
* target counts, else create only to avoid starvation |
1568 |
|
* @return true if joinMe known to be done |
1569 |
|
*/ |
1570 |
< |
final boolean preJoin(ForkJoinTask<?> joinMe, boolean maintainParallelism) { |
1570 |
> |
final boolean preJoin(ForkJoinTask<?> joinMe, |
1571 |
> |
boolean maintainParallelism) { |
1572 |
|
maintainParallelism &= maintainsParallelism; // overrride |
1573 |
|
boolean dec = false; // true when running count decremented |
1574 |
|
while (spareStack == null || !tryResumeSpare(dec)) { |
1575 |
|
int counts = workerCounts; |
1576 |
< |
if (dec || (dec = casWorkerCounts(counts, --counts))) { // CAS cheat |
1576 |
> |
if (dec || (dec = casWorkerCounts(counts, --counts))) { |
1577 |
|
if (!needSpare(counts, maintainParallelism)) |
1578 |
|
break; |
1579 |
|
if (joinMe.status < 0) |
1588 |
|
/** |
1589 |
|
* Same idea as preJoin |
1590 |
|
*/ |
1591 |
< |
final boolean preBlock(ManagedBlocker blocker, boolean maintainParallelism){ |
1591 |
> |
final boolean preBlock(ManagedBlocker blocker, |
1592 |
> |
boolean maintainParallelism) { |
1593 |
|
maintainParallelism &= maintainsParallelism; |
1594 |
|
boolean dec = false; |
1595 |
|
while (spareStack == null || !tryResumeSpare(dec)) { |
1607 |
|
} |
1608 |
|
|
1609 |
|
/** |
1610 |
< |
* Returns true if a spare thread appears to be needed. If |
1611 |
< |
* maintaining parallelism, returns true when the deficit in |
1610 |
> |
* Returns {@code true} if a spare thread appears to be needed. |
1611 |
> |
* If maintaining parallelism, returns true when the deficit in |
1612 |
|
* running threads is more than the surplus of total threads, and |
1613 |
|
* there is apparently some work to do. This self-limiting rule |
1614 |
|
* means that the more threads that have already been added, the |
1615 |
|
* less parallelism we will tolerate before adding another. |
1616 |
+ |
* |
1617 |
|
* @param counts current worker counts |
1618 |
|
* @param maintainParallelism try to maintain parallelism |
1619 |
|
*/ |
1633 |
|
/** |
1634 |
|
* Adds a spare worker if lock available and no more than the |
1635 |
|
* expected numbers of threads exist. |
1636 |
+ |
* |
1637 |
|
* @return true if successful |
1638 |
|
*/ |
1639 |
|
private boolean tryAddSpare(int expectedCounts) { |
1678 |
|
for (k = 0; k < len && ws[k] != null; ++k) |
1679 |
|
; |
1680 |
|
} |
1681 |
< |
if (k < len && !isTerminating() && (w = createWorker(k)) != null) { |
1681 |
> |
if (k < len && isProcessingTasks() && (w = createWorker(k)) != null) { |
1682 |
|
ws[k] = w; |
1683 |
|
w.start(); |
1684 |
|
} |
1693 |
|
* the same WaitQueueNodes as barriers. They are resumed mainly |
1694 |
|
* in preJoin, but are also woken on pool events that require all |
1695 |
|
* threads to check run state. |
1696 |
+ |
* |
1697 |
|
* @param w the caller |
1698 |
|
*/ |
1699 |
|
private boolean suspendIfSpare(ForkJoinWorkerThread w) { |
1700 |
|
WaitQueueNode node = null; |
1701 |
< |
int s; |
1702 |
< |
while (parallelism < runningCountOf(s = workerCounts)) { |
1701 |
> |
for (;;) { |
1702 |
> |
int s = workerCounts; |
1703 |
> |
int rc = runningCountOf(s); |
1704 |
> |
int tc = totalCountOf(s); |
1705 |
> |
int ps = parallelism; |
1706 |
> |
// use tc as bound if rc transiently out of sync |
1707 |
> |
if (tc <= ps || rc <= ps) |
1708 |
> |
return false; // not a spare |
1709 |
|
if (node == null) |
1710 |
|
node = new WaitQueueNode(0, w); |
1711 |
< |
if (casWorkerCounts(s, s-1)) { // representation-dependent |
1712 |
< |
// push onto stack |
1622 |
< |
do;while (!casSpareStack(node.next = spareStack, node)); |
1623 |
< |
// block until released by resumeSpare |
1624 |
< |
node.awaitSpareRelease(); |
1625 |
< |
return true; |
1626 |
< |
} |
1711 |
> |
if (casWorkerCounts(s, workerCountsFor(tc, rc - 1))) |
1712 |
> |
break; |
1713 |
|
} |
1714 |
< |
return false; |
1714 |
> |
// push onto stack |
1715 |
> |
do {} while (!casSpareStack(node.next = spareStack, node)); |
1716 |
> |
// block until released by resumeSpare |
1717 |
> |
while (!Thread.interrupted() && node.thread != null) |
1718 |
> |
LockSupport.park(this); |
1719 |
> |
return true; |
1720 |
|
} |
1721 |
|
|
1722 |
|
/** |
1723 |
|
* Tries to pop and resume a spare thread. |
1724 |
+ |
* |
1725 |
|
* @param updateCount if true, increment running count on success |
1726 |
|
* @return true if successful |
1727 |
|
*/ |
1740 |
|
|
1741 |
|
/** |
1742 |
|
* Pops and resumes all spare threads. Same idea as ensureSync. |
1743 |
+ |
* |
1744 |
|
* @return true if any spares released |
1745 |
|
*/ |
1746 |
|
private boolean resumeAllSpares() { |
1782 |
|
|
1783 |
|
/** |
1784 |
|
* Interface for extending managed parallelism for tasks running |
1785 |
< |
* in ForkJoinPools. A ManagedBlocker provides two methods. |
1786 |
< |
* Method {@code isReleasable} must return true if blocking is not |
1787 |
< |
* necessary. Method {@code block} blocks the current thread |
1788 |
< |
* if necessary (perhaps internally invoking isReleasable before |
1789 |
< |
* actually blocking.). |
1785 |
> |
* in {@link ForkJoinPool}s. |
1786 |
> |
* |
1787 |
> |
* <p>A {@code ManagedBlocker} provides two methods. |
1788 |
> |
* Method {@code isReleasable} must return {@code true} if |
1789 |
> |
* blocking is not necessary. Method {@code block} blocks the |
1790 |
> |
* current thread if necessary (perhaps internally invoking |
1791 |
> |
* {@code isReleasable} before actually blocking). |
1792 |
> |
* |
1793 |
|
* <p>For example, here is a ManagedBlocker based on a |
1794 |
|
* ReentrantLock: |
1795 |
< |
* <pre> |
1796 |
< |
* class ManagedLocker implements ManagedBlocker { |
1797 |
< |
* final ReentrantLock lock; |
1798 |
< |
* boolean hasLock = false; |
1799 |
< |
* ManagedLocker(ReentrantLock lock) { this.lock = lock; } |
1800 |
< |
* public boolean block() { |
1801 |
< |
* if (!hasLock) |
1802 |
< |
* lock.lock(); |
1803 |
< |
* return true; |
1804 |
< |
* } |
1805 |
< |
* public boolean isReleasable() { |
1806 |
< |
* return hasLock || (hasLock = lock.tryLock()); |
1711 |
< |
* } |
1795 |
> |
* <pre> {@code |
1796 |
> |
* class ManagedLocker implements ManagedBlocker { |
1797 |
> |
* final ReentrantLock lock; |
1798 |
> |
* boolean hasLock = false; |
1799 |
> |
* ManagedLocker(ReentrantLock lock) { this.lock = lock; } |
1800 |
> |
* public boolean block() { |
1801 |
> |
* if (!hasLock) |
1802 |
> |
* lock.lock(); |
1803 |
> |
* return true; |
1804 |
> |
* } |
1805 |
> |
* public boolean isReleasable() { |
1806 |
> |
* return hasLock || (hasLock = lock.tryLock()); |
1807 |
|
* } |
1808 |
< |
* </pre> |
1808 |
> |
* }}</pre> |
1809 |
|
*/ |
1810 |
|
public static interface ManagedBlocker { |
1811 |
|
/** |
1812 |
|
* Possibly blocks the current thread, for example waiting for |
1813 |
|
* a lock or condition. |
1814 |
< |
* @return true if no additional blocking is necessary (i.e., |
1815 |
< |
* if isReleasable would return true). |
1814 |
> |
* |
1815 |
> |
* @return {@code true} if no additional blocking is necessary |
1816 |
> |
* (i.e., if isReleasable would return true) |
1817 |
|
* @throws InterruptedException if interrupted while waiting |
1818 |
< |
* (the method is not required to do so, but is allowed to). |
1818 |
> |
* (the method is not required to do so, but is allowed to) |
1819 |
|
*/ |
1820 |
|
boolean block() throws InterruptedException; |
1821 |
|
|
1822 |
|
/** |
1823 |
< |
* Returns true if blocking is unnecessary. |
1823 |
> |
* Returns {@code true} if blocking is unnecessary. |
1824 |
|
*/ |
1825 |
|
boolean isReleasable(); |
1826 |
|
} |
1827 |
|
|
1828 |
|
/** |
1829 |
|
* Blocks in accord with the given blocker. If the current thread |
1830 |
< |
* is a ForkJoinWorkerThread, this method possibly arranges for a |
1831 |
< |
* spare thread to be activated if necessary to ensure parallelism |
1832 |
< |
* while the current thread is blocked. If |
1833 |
< |
* {@code maintainParallelism} is true and the pool supports |
1834 |
< |
* it ({@link #getMaintainsParallelism}), this method attempts to |
1835 |
< |
* maintain the pool's nominal parallelism. Otherwise if activates |
1836 |
< |
* a thread only if necessary to avoid complete starvation. This |
1837 |
< |
* option may be preferable when blockages use timeouts, or are |
1838 |
< |
* almost always brief. |
1839 |
< |
* |
1840 |
< |
* <p> If the caller is not a ForkJoinTask, this method is behaviorally |
1841 |
< |
* equivalent to |
1842 |
< |
* <pre> |
1843 |
< |
* while (!blocker.isReleasable()) |
1844 |
< |
* if (blocker.block()) |
1845 |
< |
* return; |
1846 |
< |
* </pre> |
1847 |
< |
* If the caller is a ForkJoinTask, then the pool may first |
1848 |
< |
* be expanded to ensure parallelism, and later adjusted. |
1830 |
> |
* is a {@link ForkJoinWorkerThread}, this method possibly |
1831 |
> |
* arranges for a spare thread to be activated if necessary to |
1832 |
> |
* ensure parallelism while the current thread is blocked. |
1833 |
> |
* |
1834 |
> |
* <p>If {@code maintainParallelism} is {@code true} and the pool |
1835 |
> |
* supports it ({@link #getMaintainsParallelism}), this method |
1836 |
> |
* attempts to maintain the pool's nominal parallelism. Otherwise |
1837 |
> |
* it activates a thread only if necessary to avoid complete |
1838 |
> |
* starvation. This option may be preferable when blockages use |
1839 |
> |
* timeouts, or are almost always brief. |
1840 |
> |
* |
1841 |
> |
* <p>If the caller is not a {@link ForkJoinTask}, this method is |
1842 |
> |
* behaviorally equivalent to |
1843 |
> |
* <pre> {@code |
1844 |
> |
* while (!blocker.isReleasable()) |
1845 |
> |
* if (blocker.block()) |
1846 |
> |
* return; |
1847 |
> |
* }</pre> |
1848 |
> |
* |
1849 |
> |
* If the caller is a {@code ForkJoinTask}, then the pool may |
1850 |
> |
* first be expanded to ensure parallelism, and later adjusted. |
1851 |
|
* |
1852 |
|
* @param blocker the blocker |
1853 |
< |
* @param maintainParallelism if true and supported by this pool, |
1854 |
< |
* attempt to maintain the pool's nominal parallelism; otherwise |
1855 |
< |
* activate a thread only if necessary to avoid complete |
1856 |
< |
* starvation. |
1857 |
< |
* @throws InterruptedException if blocker.block did so. |
1853 |
> |
* @param maintainParallelism if {@code true} and supported by |
1854 |
> |
* this pool, attempt to maintain the pool's nominal parallelism; |
1855 |
> |
* otherwise activate a thread only if necessary to avoid |
1856 |
> |
* complete starvation. |
1857 |
> |
* @throws InterruptedException if blocker.block did so |
1858 |
|
*/ |
1859 |
|
public static void managedBlock(ManagedBlocker blocker, |
1860 |
|
boolean maintainParallelism) |
1861 |
|
throws InterruptedException { |
1862 |
|
Thread t = Thread.currentThread(); |
1863 |
< |
ForkJoinPool pool = (t instanceof ForkJoinWorkerThread? |
1864 |
< |
((ForkJoinWorkerThread)t).pool : null); |
1863 |
> |
ForkJoinPool pool = ((t instanceof ForkJoinWorkerThread) ? |
1864 |
> |
((ForkJoinWorkerThread) t).pool : null); |
1865 |
|
if (!blocker.isReleasable()) { |
1866 |
|
try { |
1867 |
|
if (pool == null || |
1876 |
|
|
1877 |
|
private static void awaitBlocker(ManagedBlocker blocker) |
1878 |
|
throws InterruptedException { |
1879 |
< |
do;while (!blocker.isReleasable() && !blocker.block()); |
1879 |
> |
do {} while (!blocker.isReleasable() && !blocker.block()); |
1880 |
|
} |
1881 |
|
|
1882 |
< |
// AbstractExecutorService overrides |
1882 |
> |
// AbstractExecutorService overrides. These rely on undocumented |
1883 |
> |
// fact that ForkJoinTask.adapt returns ForkJoinTasks that also |
1884 |
> |
// implement RunnableFuture. |
1885 |
|
|
1886 |
|
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) { |
1887 |
< |
return new AdaptedRunnable(runnable, value); |
1887 |
> |
return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value); |
1888 |
|
} |
1889 |
|
|
1890 |
|
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) { |
1891 |
< |
return new AdaptedCallable(callable); |
1792 |
< |
} |
1793 |
< |
|
1794 |
< |
|
1795 |
< |
// Temporary Unsafe mechanics for preliminary release |
1796 |
< |
private static Unsafe getUnsafe() throws Throwable { |
1797 |
< |
try { |
1798 |
< |
return Unsafe.getUnsafe(); |
1799 |
< |
} catch (SecurityException se) { |
1800 |
< |
try { |
1801 |
< |
return java.security.AccessController.doPrivileged |
1802 |
< |
(new java.security.PrivilegedExceptionAction<Unsafe>() { |
1803 |
< |
public Unsafe run() throws Exception { |
1804 |
< |
return getUnsafePrivileged(); |
1805 |
< |
}}); |
1806 |
< |
} catch (java.security.PrivilegedActionException e) { |
1807 |
< |
throw e.getCause(); |
1808 |
< |
} |
1809 |
< |
} |
1891 |
> |
return (RunnableFuture<T>) ForkJoinTask.adapt(callable); |
1892 |
|
} |
1893 |
|
|
1894 |
< |
private static Unsafe getUnsafePrivileged() |
1813 |
< |
throws NoSuchFieldException, IllegalAccessException { |
1814 |
< |
Field f = Unsafe.class.getDeclaredField("theUnsafe"); |
1815 |
< |
f.setAccessible(true); |
1816 |
< |
return (Unsafe) f.get(null); |
1817 |
< |
} |
1818 |
< |
|
1819 |
< |
private static long fieldOffset(String fieldName) |
1820 |
< |
throws NoSuchFieldException { |
1821 |
< |
return _unsafe.objectFieldOffset |
1822 |
< |
(ForkJoinPool.class.getDeclaredField(fieldName)); |
1823 |
< |
} |
1894 |
> |
// Unsafe mechanics |
1895 |
|
|
1896 |
< |
static final Unsafe _unsafe; |
1897 |
< |
static final long eventCountOffset; |
1898 |
< |
static final long workerCountsOffset; |
1899 |
< |
static final long runControlOffset; |
1900 |
< |
static final long syncStackOffset; |
1901 |
< |
static final long spareStackOffset; |
1902 |
< |
|
1903 |
< |
static { |
1904 |
< |
try { |
1905 |
< |
_unsafe = getUnsafe(); |
1906 |
< |
eventCountOffset = fieldOffset("eventCount"); |
1836 |
< |
workerCountsOffset = fieldOffset("workerCounts"); |
1837 |
< |
runControlOffset = fieldOffset("runControl"); |
1838 |
< |
syncStackOffset = fieldOffset("syncStack"); |
1839 |
< |
spareStackOffset = fieldOffset("spareStack"); |
1840 |
< |
} catch (Throwable e) { |
1841 |
< |
throw new RuntimeException("Could not initialize intrinsics", e); |
1842 |
< |
} |
1843 |
< |
} |
1896 |
> |
private static final sun.misc.Unsafe UNSAFE = getUnsafe(); |
1897 |
> |
private static final long eventCountOffset = |
1898 |
> |
objectFieldOffset("eventCount", ForkJoinPool.class); |
1899 |
> |
private static final long workerCountsOffset = |
1900 |
> |
objectFieldOffset("workerCounts", ForkJoinPool.class); |
1901 |
> |
private static final long runControlOffset = |
1902 |
> |
objectFieldOffset("runControl", ForkJoinPool.class); |
1903 |
> |
private static final long syncStackOffset = |
1904 |
> |
objectFieldOffset("syncStack",ForkJoinPool.class); |
1905 |
> |
private static final long spareStackOffset = |
1906 |
> |
objectFieldOffset("spareStack", ForkJoinPool.class); |
1907 |
|
|
1908 |
|
private boolean casEventCount(long cmp, long val) { |
1909 |
< |
return _unsafe.compareAndSwapLong(this, eventCountOffset, cmp, val); |
1909 |
> |
return UNSAFE.compareAndSwapLong(this, eventCountOffset, cmp, val); |
1910 |
|
} |
1911 |
|
private boolean casWorkerCounts(int cmp, int val) { |
1912 |
< |
return _unsafe.compareAndSwapInt(this, workerCountsOffset, cmp, val); |
1912 |
> |
return UNSAFE.compareAndSwapInt(this, workerCountsOffset, cmp, val); |
1913 |
|
} |
1914 |
|
private boolean casRunControl(int cmp, int val) { |
1915 |
< |
return _unsafe.compareAndSwapInt(this, runControlOffset, cmp, val); |
1915 |
> |
return UNSAFE.compareAndSwapInt(this, runControlOffset, cmp, val); |
1916 |
|
} |
1917 |
|
private boolean casSpareStack(WaitQueueNode cmp, WaitQueueNode val) { |
1918 |
< |
return _unsafe.compareAndSwapObject(this, spareStackOffset, cmp, val); |
1918 |
> |
return UNSAFE.compareAndSwapObject(this, spareStackOffset, cmp, val); |
1919 |
|
} |
1920 |
|
private boolean casBarrierStack(WaitQueueNode cmp, WaitQueueNode val) { |
1921 |
< |
return _unsafe.compareAndSwapObject(this, syncStackOffset, cmp, val); |
1921 |
> |
return UNSAFE.compareAndSwapObject(this, syncStackOffset, cmp, val); |
1922 |
> |
} |
1923 |
> |
|
1924 |
> |
private static long objectFieldOffset(String field, Class<?> klazz) { |
1925 |
> |
try { |
1926 |
> |
return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field)); |
1927 |
> |
} catch (NoSuchFieldException e) { |
1928 |
> |
// Convert Exception to corresponding Error |
1929 |
> |
NoSuchFieldError error = new NoSuchFieldError(field); |
1930 |
> |
error.initCause(e); |
1931 |
> |
throw error; |
1932 |
> |
} |
1933 |
> |
} |
1934 |
> |
|
1935 |
> |
/** |
1936 |
> |
* Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. |
1937 |
> |
* Replace with a simple call to Unsafe.getUnsafe when integrating |
1938 |
> |
* into a jdk. |
1939 |
> |
* |
1940 |
> |
* @return a sun.misc.Unsafe |
1941 |
> |
*/ |
1942 |
> |
private static sun.misc.Unsafe getUnsafe() { |
1943 |
> |
try { |
1944 |
> |
return sun.misc.Unsafe.getUnsafe(); |
1945 |
> |
} catch (SecurityException se) { |
1946 |
> |
try { |
1947 |
> |
return java.security.AccessController.doPrivileged |
1948 |
> |
(new java.security |
1949 |
> |
.PrivilegedExceptionAction<sun.misc.Unsafe>() { |
1950 |
> |
public sun.misc.Unsafe run() throws Exception { |
1951 |
> |
java.lang.reflect.Field f = sun.misc |
1952 |
> |
.Unsafe.class.getDeclaredField("theUnsafe"); |
1953 |
> |
f.setAccessible(true); |
1954 |
> |
return (sun.misc.Unsafe) f.get(null); |
1955 |
> |
}}); |
1956 |
> |
} catch (java.security.PrivilegedActionException e) { |
1957 |
> |
throw new RuntimeException("Could not initialize intrinsics", |
1958 |
> |
e.getCause()); |
1959 |
> |
} |
1960 |
> |
} |
1961 |
|
} |
1962 |
|
} |