21 |
|
import java.util.concurrent.TimeUnit; |
22 |
|
import java.util.concurrent.atomic.AtomicInteger; |
23 |
|
import java.util.concurrent.atomic.AtomicLong; |
24 |
< |
import java.util.concurrent.locks.ReentrantLock; |
24 |
> |
import java.util.concurrent.locks.AbstractQueuedSynchronizer; |
25 |
|
import java.util.concurrent.locks.Condition; |
26 |
|
|
27 |
|
/** |
42 |
|
* ForkJoinPool}s may also be appropriate for use with event-style |
43 |
|
* tasks that are never joined. |
44 |
|
* |
45 |
< |
* <p>A {@code ForkJoinPool} is constructed with a given target |
46 |
< |
* parallelism level; by default, equal to the number of available |
47 |
< |
* processors. The pool attempts to maintain enough active (or |
48 |
< |
* available) threads by dynamically adding, suspending, or resuming |
49 |
< |
* internal worker threads, even if some tasks are stalled waiting to |
50 |
< |
* join others. However, no such adjustments are guaranteed in the |
51 |
< |
* face of blocked IO or other unmanaged synchronization. The nested |
52 |
< |
* {@link ManagedBlocker} interface enables extension of the kinds of |
45 |
> |
* <p>A static {@link #commonPool} is available and appropriate for |
46 |
> |
* most applications. The common pool is constructed upon first |
47 |
> |
* access, or upon usage by any ForkJoinTask that is not explictly |
48 |
> |
* submitted to a specified pool. Using the common pool normally |
49 |
> |
* reduces resource usage (its threads are slowly reclaimed during |
50 |
> |
* periods of non-use, and reinstated upon subsequent use). The |
51 |
> |
* common pool is by default constructed with default parameters, but |
52 |
> |
* these may be controlled by setting any or all of the three |
53 |
> |
* properties {@code |
54 |
> |
* java.util.concurrent.ForkJoinPool.common.{parallelism, |
55 |
> |
* threadFactory, exceptionHandler}}. |
56 |
> |
* |
57 |
> |
* <p>For applications that require separate or custom pools, a {@code |
58 |
> |
* ForkJoinPool} may be constructed with a given target parallelism |
59 |
> |
* level; by default, equal to the number of available processors. The |
60 |
> |
* pool attempts to maintain enough active (or available) threads by |
61 |
> |
* dynamically adding, suspending, or resuming internal worker |
62 |
> |
* threads, even if some tasks are stalled waiting to join |
63 |
> |
* others. However, no such adjustments are guaranteed in the face of |
64 |
> |
* blocked IO or other unmanaged synchronization. The nested {@link |
65 |
> |
* ManagedBlocker} interface enables extension of the kinds of |
66 |
|
* synchronization accommodated. |
67 |
|
* |
68 |
|
* <p>In addition to execution and lifecycle control methods, this |
107 |
|
* </tr> |
108 |
|
* </table> |
109 |
|
* |
97 |
– |
* <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is |
98 |
– |
* used for all parallel task execution in a program or subsystem. |
99 |
– |
* Otherwise, use would not usually outweigh the construction and |
100 |
– |
* bookkeeping overhead of creating a large set of threads. For |
101 |
– |
* example, a common pool could be used for the {@code SortTasks} |
102 |
– |
* illustrated in {@link RecursiveAction}. Because {@code |
103 |
– |
* ForkJoinPool} uses threads in {@linkplain java.lang.Thread#isDaemon |
104 |
– |
* daemon} mode, there is typically no need to explicitly {@link |
105 |
– |
* #shutdown} such a pool upon program exit. |
106 |
– |
* |
107 |
– |
* <pre> {@code |
108 |
– |
* static final ForkJoinPool mainPool = new ForkJoinPool(); |
109 |
– |
* ... |
110 |
– |
* public void sort(long[] array) { |
111 |
– |
* mainPool.invoke(new SortTask(array, 0, array.length)); |
112 |
– |
* }}</pre> |
113 |
– |
* |
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 |
173 |
|
* If an attempted steal fails, a thief always chooses a different |
174 |
|
* random victim target to try next. So, in order for one thief to |
175 |
|
* progress, it suffices for any in-progress poll or new push on |
176 |
< |
* any empty queue to complete. |
176 |
> |
* any empty queue to complete. (This is why we normally use |
177 |
> |
* method pollAt and its variants that try once at the apparent |
178 |
> |
* base index, else consider alternative actions, rather than |
179 |
> |
* method poll.) |
180 |
|
* |
181 |
|
* This approach also enables support of a user mode in which local |
182 |
|
* task processing is in FIFO, not LIFO order, simply by using |
202 |
|
* take tasks, and they are multiplexed on to a finite number of |
203 |
|
* shared work queues. However, classes are set up so that future |
204 |
|
* extensions could allow submitters to optionally help perform |
205 |
< |
* tasks as well. Pool submissions from internal workers are also |
206 |
< |
* allowed, but use randomized rather than thread-hashed queue |
207 |
< |
* indices to avoid imbalance. Insertion of tasks in shared mode |
208 |
< |
* requires a lock (mainly to protect in the case of resizing) but |
209 |
< |
* we use only a simple spinlock (using bits in field runState), |
210 |
< |
* because submitters encountering a busy queue try or create |
212 |
< |
* others so never block. |
205 |
> |
* tasks as well. Insertion of tasks in shared mode requires a |
206 |
> |
* lock (mainly to protect in the case of resizing) but we use |
207 |
> |
* only a simple spinlock (using bits in field runState), because |
208 |
> |
* submitters encountering a busy queue move on to try or create |
209 |
> |
* other queues -- they block only when creating and registering |
210 |
> |
* new queues. |
211 |
|
* |
212 |
|
* Management |
213 |
|
* ========== |
245 |
|
* readers must tolerate null slots. Shared (submission) queues |
246 |
|
* are at even indices, worker queues at odd indices. Grouping |
247 |
|
* them together in this way simplifies and speeds up task |
248 |
< |
* scanning. To avoid flailing during start-up, the array is |
249 |
< |
* presized to hold twice #parallelism workers (which is unlikely |
250 |
< |
* to need further resizing during execution). But to avoid |
251 |
< |
* dealing with so many null slots, variable runState includes a |
254 |
< |
* mask for the nearest power of two that contains all current |
255 |
< |
* workers. All worker thread creation is on-demand, triggered by |
256 |
< |
* task submissions, replacement of terminated workers, and/or |
248 |
> |
* scanning. |
249 |
> |
* |
250 |
> |
* All worker thread creation is on-demand, triggered by task |
251 |
> |
* submissions, replacement of terminated workers, and/or |
252 |
|
* compensation for blocked workers. However, all other support |
253 |
|
* code is set up to work with other policies. To ensure that we |
254 |
|
* do not hold on to worker references that would prevent GC, ALL |
261 |
|
* both index-check and null-check the IDs. All such accesses |
262 |
|
* ignore bad IDs by returning out early from what they are doing, |
263 |
|
* since this can only be associated with termination, in which |
264 |
< |
* case it is OK to give up. |
265 |
< |
* |
266 |
< |
* All uses of the workQueues array check that it is non-null |
267 |
< |
* (even if previously non-null). This allows nulling during |
268 |
< |
* termination, which is currently not necessary, but remains an |
269 |
< |
* option for resource-revocation-based shutdown schemes. It also |
275 |
< |
* helps reduce JIT issuance of uncommon-trap code, which tends to |
264 |
> |
* case it is OK to give up. All uses of the workQueues array |
265 |
> |
* also check that it is non-null (even if previously |
266 |
> |
* non-null). This allows nulling during termination, which is |
267 |
> |
* currently not necessary, but remains an option for |
268 |
> |
* resource-revocation-based shutdown schemes. It also helps |
269 |
> |
* reduce JIT issuance of uncommon-trap code, which tends to |
270 |
|
* unnecessarily complicate control flow in some methods. |
271 |
|
* |
272 |
|
* Event Queuing. Unlike HPC work-stealing frameworks, we cannot |
317 |
|
* |
318 |
|
* Trimming workers. To release resources after periods of lack of |
319 |
|
* use, a worker starting to wait when the pool is quiescent will |
320 |
< |
* time out and terminate if the pool has remained quiescent for |
321 |
< |
* SHRINK_RATE nanosecs. This will slowly propagate, eventually |
322 |
< |
* terminating all workers after long periods of non-use. |
320 |
> |
* time out and terminate if the pool has remained quiescent for a |
321 |
> |
* given period -- a short period if there are more threads than |
322 |
> |
* parallelism, longer as the number of threads decreases. This |
323 |
> |
* will slowly propagate, eventually terminating all workers after |
324 |
> |
* periods of non-use. |
325 |
|
* |
326 |
|
* Shutdown and Termination. A call to shutdownNow atomically sets |
327 |
|
* a runState bit and then (non-atomically) sets each worker's |
379 |
|
* (http://portal.acm.org/citation.cfm?id=155354). It differs in |
380 |
|
* that: (1) We only maintain dependency links across workers upon |
381 |
|
* steals, rather than use per-task bookkeeping. This sometimes |
382 |
< |
* requires a linear scan of workers array to locate stealers, but |
383 |
< |
* often doesn't because stealers leave hints (that may become |
382 |
> |
* requires a linear scan of workQueues array to locate stealers, |
383 |
> |
* but often doesn't because stealers leave hints (that may become |
384 |
|
* stale/wrong) of where to locate them. A stealHint is only a |
385 |
|
* hint because a worker might have had multiple steals and the |
386 |
|
* hint records only one of them (usually the most current). |
391 |
|
* which means that we miss links in the chain during long-lived |
392 |
|
* tasks, GC stalls etc (which is OK since blocking in such cases |
393 |
|
* is usually a good idea). (4) We bound the number of attempts |
394 |
< |
* to find work (see MAX_HELP_DEPTH) and fall back to suspending |
395 |
< |
* the worker and if necessary replacing it with another. |
394 |
> |
* to find work (see MAX_HELP) and fall back to suspending the |
395 |
> |
* worker and if necessary replacing it with another. |
396 |
|
* |
397 |
|
* It is impossible to keep exactly the target parallelism number |
398 |
|
* of threads running at any given time. Determining the |
399 |
|
* existence of conservatively safe helping targets, the |
400 |
|
* availability of already-created spares, and the apparent need |
401 |
|
* to create new spares are all racy, so we rely on multiple |
402 |
< |
* retries of each. Currently, in keeping with on-demand |
403 |
< |
* signalling policy, we compensate only if blocking would leave |
404 |
< |
* less than one active (non-waiting, non-blocked) worker. |
405 |
< |
* Additionally, to avoid some false alarms due to GC, lagging |
406 |
< |
* counters, system activity, etc, compensated blocking for joins |
407 |
< |
* is only attempted after rechecks stabilize in |
408 |
< |
* ForkJoinTask.awaitJoin. (Retries are interspersed with |
409 |
< |
* Thread.yield, for good citizenship.) |
402 |
> |
* retries of each. Compensation in the apparent absence of |
403 |
> |
* helping opportunities is challenging to control on JVMs, where |
404 |
> |
* GC and other activities can stall progress of tasks that in |
405 |
> |
* turn stall out many other dependent tasks, without us being |
406 |
> |
* able to determine whether they will ever require compensation. |
407 |
> |
* Even though work-stealing otherwise encounters little |
408 |
> |
* degradation in the presence of more threads than cores, |
409 |
> |
* aggressively adding new threads in such cases entails risk of |
410 |
> |
* unwanted positive feedback control loops in which more threads |
411 |
> |
* cause more dependent stalls (as well as delayed progress of |
412 |
> |
* unblocked threads to the point that we know they are available) |
413 |
> |
* leading to more situations requiring more threads, and so |
414 |
> |
* on. This aspect of control can be seen as an (analytically |
415 |
> |
* intractable) game with an opponent that may choose the worst |
416 |
> |
* (for us) active thread to stall at any time. We take several |
417 |
> |
* precautions to bound losses (and thus bound gains), mainly in |
418 |
> |
* methods tryCompensate and awaitJoin: (1) We only try |
419 |
> |
* compensation after attempting enough helping steps (measured |
420 |
> |
* via counting and timing) that we have already consumed the |
421 |
> |
* estimated cost of creating and activating a new thread. (2) We |
422 |
> |
* allow up to 50% of threads to be blocked before initially |
423 |
> |
* adding any others, and unless completely saturated, check that |
424 |
> |
* some work is available for a new worker before adding. Also, we |
425 |
> |
* create up to only 50% more threads until entering a mode that |
426 |
> |
* only adds a thread if all others are possibly blocked. All |
427 |
> |
* together, this means that we might be half as fast to react, |
428 |
> |
* and create half as many threads as possible in the ideal case, |
429 |
> |
* but present vastly fewer anomalies in all other cases compared |
430 |
> |
* to both more aggressive and more conservative alternatives. |
431 |
|
* |
432 |
|
* Style notes: There is a lot of representation-level coupling |
433 |
|
* among classes ForkJoinPool, ForkJoinWorkerThread, and |
435 |
|
* managed by ForkJoinPool, so are directly accessed. There is |
436 |
|
* little point trying to reduce this, since any associated future |
437 |
|
* changes in representations will need to be accompanied by |
438 |
< |
* algorithmic changes anyway. All together, these low-level |
439 |
< |
* implementation choices produce as much as a factor of 4 |
440 |
< |
* performance improvement compared to naive implementations, and |
441 |
< |
* enable the processing of billions of tasks per second, at the |
442 |
< |
* expense of some ugliness. |
443 |
< |
* |
444 |
< |
* Methods signalWork() and scan() are the main bottlenecks, so are |
445 |
< |
* especially heavily micro-optimized/mangled. There are lots of |
446 |
< |
* inline assignments (of form "while ((local = field) != 0)") |
447 |
< |
* which are usually the simplest way to ensure the required read |
448 |
< |
* orderings (which are sometimes critical). This leads to a |
449 |
< |
* "C"-like style of listing declarations of these locals at the |
450 |
< |
* heads of methods or blocks. There are several occurrences of |
451 |
< |
* the unusual "do {} while (!cas...)" which is the simplest way |
435 |
< |
* to force an update of a CAS'ed variable. There are also other |
436 |
< |
* coding oddities that help some methods perform reasonably even |
437 |
< |
* when interpreted (not compiled). |
438 |
> |
* algorithmic changes anyway. Several methods intrinsically |
439 |
> |
* sprawl because they must accumulate sets of consistent reads of |
440 |
> |
* volatiles held in local variables. Methods signalWork() and |
441 |
> |
* scan() are the main bottlenecks, so are especially heavily |
442 |
> |
* micro-optimized/mangled. There are lots of inline assignments |
443 |
> |
* (of form "while ((local = field) != 0)") which are usually the |
444 |
> |
* simplest way to ensure the required read orderings (which are |
445 |
> |
* sometimes critical). This leads to a "C"-like style of listing |
446 |
> |
* declarations of these locals at the heads of methods or blocks. |
447 |
> |
* There are several occurrences of the unusual "do {} while |
448 |
> |
* (!cas...)" which is the simplest way to force an update of a |
449 |
> |
* CAS'ed variable. There are also other coding oddities that help |
450 |
> |
* some methods perform reasonably even when interpreted (not |
451 |
> |
* compiled). |
452 |
|
* |
453 |
|
* The order of declarations in this file is: |
454 |
< |
* (1) statics |
455 |
< |
* (2) fields (along with constants used when unpacking some of |
456 |
< |
* them), listed in an order that tends to reduce contention |
457 |
< |
* among them a bit under most JVMs; |
458 |
< |
* (3) nested classes |
459 |
< |
* (4) internal control methods |
460 |
< |
* (5) callbacks and other support for ForkJoinTask methods |
461 |
< |
* (6) exported methods (plus a few little helpers) |
462 |
< |
* (7) static block initializing all statics in a minimally |
463 |
< |
* dependent order. |
454 |
> |
* (1) Static utility functions |
455 |
> |
* (2) Nested (static) classes |
456 |
> |
* (3) Static fields |
457 |
> |
* (4) Fields, along with constants used when unpacking some of them |
458 |
> |
* (5) Internal control methods |
459 |
> |
* (6) Callbacks and other support for ForkJoinTask methods |
460 |
> |
* (7) Exported methods |
461 |
> |
* (8) Static block initializing statics in minimally dependent order |
462 |
> |
*/ |
463 |
> |
|
464 |
> |
// Static utilities |
465 |
> |
|
466 |
> |
/** |
467 |
> |
* If there is a security manager, makes sure caller has |
468 |
> |
* permission to modify threads. |
469 |
|
*/ |
470 |
+ |
private static void checkPermission() { |
471 |
+ |
SecurityManager security = System.getSecurityManager(); |
472 |
+ |
if (security != null) |
473 |
+ |
security.checkPermission(modifyThreadPermission); |
474 |
+ |
} |
475 |
+ |
|
476 |
+ |
// Nested classes |
477 |
|
|
478 |
|
/** |
479 |
|
* Factory for creating new {@link ForkJoinWorkerThread}s. |
503 |
|
} |
504 |
|
|
505 |
|
/** |
506 |
< |
* Creates a new ForkJoinWorkerThread. This factory is used unless |
507 |
< |
* overridden in ForkJoinPool constructors. |
508 |
< |
*/ |
509 |
< |
public static final ForkJoinWorkerThreadFactory |
510 |
< |
defaultForkJoinWorkerThreadFactory; |
511 |
< |
|
512 |
< |
/** |
513 |
< |
* Permission required for callers of methods that may start or |
514 |
< |
* kill threads. |
515 |
< |
*/ |
516 |
< |
private static final RuntimePermission modifyThreadPermission; |
517 |
< |
|
518 |
< |
/** |
519 |
< |
* If there is a security manager, makes sure caller has |
520 |
< |
* permission to modify threads. |
521 |
< |
*/ |
522 |
< |
private static void checkPermission() { |
523 |
< |
SecurityManager security = System.getSecurityManager(); |
524 |
< |
if (security != null) |
525 |
< |
security.checkPermission(modifyThreadPermission); |
506 |
> |
* A simple non-reentrant lock used for exclusion when managing |
507 |
> |
* queues and workers. We use a custom lock so that we can readily |
508 |
> |
* probe lock state in constructions that check among alternative |
509 |
> |
* actions. The lock is normally only very briefly held, and |
510 |
> |
* sometimes treated as a spinlock, but other usages block to |
511 |
> |
* reduce overall contention in those cases where locked code |
512 |
> |
* bodies perform allocation/resizing. |
513 |
> |
*/ |
514 |
> |
static final class Mutex extends AbstractQueuedSynchronizer { |
515 |
> |
public final boolean tryAcquire(int ignore) { |
516 |
> |
return compareAndSetState(0, 1); |
517 |
> |
} |
518 |
> |
public final boolean tryRelease(int ignore) { |
519 |
> |
setState(0); |
520 |
> |
return true; |
521 |
> |
} |
522 |
> |
public final void lock() { acquire(0); } |
523 |
> |
public final void unlock() { release(0); } |
524 |
> |
public final boolean isHeldExclusively() { return getState() == 1; } |
525 |
> |
public final Condition newCondition() { return new ConditionObject(); } |
526 |
|
} |
527 |
|
|
528 |
|
/** |
529 |
< |
* Generator for assigning sequence numbers as pool names. |
530 |
< |
*/ |
531 |
< |
private static final AtomicInteger poolNumberGenerator; |
532 |
< |
|
507 |
< |
/** |
508 |
< |
* Bits and masks for control variables |
509 |
< |
* |
510 |
< |
* Field ctl is a long packed with: |
511 |
< |
* AC: Number of active running workers minus target parallelism (16 bits) |
512 |
< |
* TC: Number of total workers minus target parallelism (16 bits) |
513 |
< |
* ST: true if pool is terminating (1 bit) |
514 |
< |
* EC: the wait count of top waiting thread (15 bits) |
515 |
< |
* ID: ~(poolIndex >>> 1) of top of Treiber stack of waiters (16 bits) |
516 |
< |
* |
517 |
< |
* When convenient, we can extract the upper 32 bits of counts and |
518 |
< |
* the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e = |
519 |
< |
* (int)ctl. The ec field is never accessed alone, but always |
520 |
< |
* together with id and st. The offsets of counts by the target |
521 |
< |
* parallelism and the positionings of fields makes it possible to |
522 |
< |
* perform the most common checks via sign tests of fields: When |
523 |
< |
* ac is negative, there are not enough active workers, when tc is |
524 |
< |
* negative, there are not enough total workers, when id is |
525 |
< |
* negative, there is at least one waiting worker, and when e is |
526 |
< |
* negative, the pool is terminating. To deal with these possibly |
527 |
< |
* negative fields, we use casts in and out of "short" and/or |
528 |
< |
* signed shifts to maintain signedness. |
529 |
< |
* |
530 |
< |
* When a thread is queued (inactivated), its eventCount field is |
531 |
< |
* negative, which is the only way to tell if a worker is |
532 |
< |
* prevented from executing tasks, even though it must continue to |
533 |
< |
* scan for them to avoid queuing races. |
534 |
< |
* |
535 |
< |
* Field runState is an int packed with: |
536 |
< |
* SHUTDOWN: true if shutdown is enabled (1 bit) |
537 |
< |
* SEQ: a sequence number updated upon (de)registering workers (15 bits) |
538 |
< |
* MASK: mask (power of 2 - 1) covering all registered poolIndexes (16 bits) |
539 |
< |
* |
540 |
< |
* The combination of mask and sequence number enables simple |
541 |
< |
* consistency checks: Staleness of read-only operations on the |
542 |
< |
* workers and queues arrays can be checked by comparing runState |
543 |
< |
* before vs after the reads. The low 16 bits (i.e, anding with |
544 |
< |
* SMASK) hold the smallest power of two covering all worker |
545 |
< |
* indices, minus one. The mask for queues (vs workers) is twice |
546 |
< |
* this value plus 1. |
547 |
< |
*/ |
548 |
< |
|
549 |
< |
// bit positions/shifts for fields |
550 |
< |
private static final int AC_SHIFT = 48; |
551 |
< |
private static final int TC_SHIFT = 32; |
552 |
< |
private static final int ST_SHIFT = 31; |
553 |
< |
private static final int EC_SHIFT = 16; |
554 |
< |
|
555 |
< |
// bounds |
556 |
< |
private static final int MAX_ID = 0x7fff; // max poolIndex |
557 |
< |
private static final int SMASK = 0xffff; // mask short bits |
558 |
< |
private static final int SHORT_SIGN = 1 << 15; |
559 |
< |
private static final int INT_SIGN = 1 << 31; |
560 |
< |
|
561 |
< |
// masks |
562 |
< |
private static final long STOP_BIT = 0x0001L << ST_SHIFT; |
563 |
< |
private static final long AC_MASK = ((long)SMASK) << AC_SHIFT; |
564 |
< |
private static final long TC_MASK = ((long)SMASK) << TC_SHIFT; |
565 |
< |
|
566 |
< |
// units for incrementing and decrementing |
567 |
< |
private static final long TC_UNIT = 1L << TC_SHIFT; |
568 |
< |
private static final long AC_UNIT = 1L << AC_SHIFT; |
569 |
< |
|
570 |
< |
// masks and units for dealing with u = (int)(ctl >>> 32) |
571 |
< |
private static final int UAC_SHIFT = AC_SHIFT - 32; |
572 |
< |
private static final int UTC_SHIFT = TC_SHIFT - 32; |
573 |
< |
private static final int UAC_MASK = SMASK << UAC_SHIFT; |
574 |
< |
private static final int UTC_MASK = SMASK << UTC_SHIFT; |
575 |
< |
private static final int UAC_UNIT = 1 << UAC_SHIFT; |
576 |
< |
private static final int UTC_UNIT = 1 << UTC_SHIFT; |
577 |
< |
|
578 |
< |
// masks and units for dealing with e = (int)ctl |
579 |
< |
private static final int E_MASK = 0x7fffffff; // no STOP_BIT |
580 |
< |
private static final int E_SEQ = 1 << EC_SHIFT; |
581 |
< |
|
582 |
< |
// runState bits |
583 |
< |
private static final int SHUTDOWN = 1 << 31; |
584 |
< |
private static final int RS_SEQ = 1 << 16; |
585 |
< |
private static final int RS_SEQ_MASK = 0x7fff0000; |
586 |
< |
|
587 |
< |
// access mode for WorkQueue |
588 |
< |
static final int LIFO_QUEUE = 0; |
589 |
< |
static final int FIFO_QUEUE = 1; |
590 |
< |
static final int SHARED_QUEUE = -1; |
591 |
< |
|
592 |
< |
/** |
593 |
< |
* The wakeup interval (in nanoseconds) for a worker waiting for a |
594 |
< |
* task when the pool is quiescent to instead try to shrink the |
595 |
< |
* number of workers. The exact value does not matter too |
596 |
< |
* much. It must be short enough to release resources during |
597 |
< |
* sustained periods of idleness, but not so short that threads |
598 |
< |
* are continually re-created. |
599 |
< |
*/ |
600 |
< |
private static final long SHRINK_RATE = |
601 |
< |
4L * 1000L * 1000L * 1000L; // 4 seconds |
602 |
< |
|
603 |
< |
/** |
604 |
< |
* The timeout value for attempted shrinkage, includes |
605 |
< |
* some slop to cope with system timer imprecision. |
606 |
< |
*/ |
607 |
< |
private static final long SHRINK_TIMEOUT = SHRINK_RATE - (SHRINK_RATE / 10); |
608 |
< |
|
609 |
< |
/** |
610 |
< |
* The maximum stolen->joining link depth allowed in tryHelpStealer. |
611 |
< |
* Depths for legitimate chains are unbounded, but we use a fixed |
612 |
< |
* constant to avoid (otherwise unchecked) cycles and to bound |
613 |
< |
* staleness of traversal parameters at the expense of sometimes |
614 |
< |
* blocking when we could be helping. |
615 |
< |
*/ |
616 |
< |
private static final int MAX_HELP_DEPTH = 16; |
617 |
< |
|
618 |
< |
/* |
619 |
< |
* Field layout order in this class tends to matter more than one |
620 |
< |
* would like. Runtime layout order is only loosely related to |
621 |
< |
* declaration order and may differ across JVMs, but the following |
622 |
< |
* empirically works OK on current JVMs. |
529 |
> |
* Class for artificial tasks that are used to replace the target |
530 |
> |
* of local joins if they are removed from an interior queue slot |
531 |
> |
* in WorkQueue.tryRemoveAndExec. We don't need the proxy to |
532 |
> |
* actually do anything beyond having a unique identity. |
533 |
|
*/ |
534 |
< |
|
535 |
< |
volatile long ctl; // main pool control |
536 |
< |
final int parallelism; // parallelism level |
537 |
< |
final int localMode; // per-worker scheduling mode |
538 |
< |
int nextPoolIndex; // hint used in registerWorker |
539 |
< |
volatile int runState; // shutdown status, seq, and mask |
630 |
< |
WorkQueue[] workQueues; // main registry |
631 |
< |
final ReentrantLock lock; // for registration |
632 |
< |
final Condition termination; // for awaitTermination |
633 |
< |
final ForkJoinWorkerThreadFactory factory; // factory for new workers |
634 |
< |
final Thread.UncaughtExceptionHandler ueh; // per-worker UEH |
635 |
< |
final AtomicLong stealCount; // collect counts when terminated |
636 |
< |
final AtomicInteger nextWorkerNumber; // to create worker name string |
637 |
< |
final String workerNamePrefix; // Prefix for assigning worker names |
534 |
> |
static final class EmptyTask extends ForkJoinTask<Void> { |
535 |
> |
EmptyTask() { status = ForkJoinTask.NORMAL; } // force done |
536 |
> |
public final Void getRawResult() { return null; } |
537 |
> |
public final void setRawResult(Void x) {} |
538 |
> |
public final boolean exec() { return true; } |
539 |
> |
} |
540 |
|
|
541 |
|
/** |
542 |
|
* Queues supporting work-stealing as well as external task |
587 |
|
* avoiding really bad worst-case access. (Until better JVM |
588 |
|
* support is in place, this padding is dependent on transient |
589 |
|
* properties of JVM field layout rules.) We also take care in |
590 |
< |
* allocating and sizing and resizing the array. Non-shared queue |
590 |
> |
* allocating, sizing and resizing the array. Non-shared queue |
591 |
|
* arrays are initialized (via method growArray) by workers before |
592 |
|
* use. Others are allocated on first use. |
593 |
|
*/ |
594 |
|
static final class WorkQueue { |
595 |
|
/** |
596 |
|
* Capacity of work-stealing queue array upon initialization. |
597 |
< |
* Must be a power of two; at least 4, but set larger to |
598 |
< |
* reduce cacheline sharing among queues. |
597 |
> |
* Must be a power of two; at least 4, but should be larger to |
598 |
> |
* reduce or eliminate cacheline sharing among queues. |
599 |
> |
* Currently, it is much larger, as a partial workaround for |
600 |
> |
* the fact that JVMs often place arrays in locations that |
601 |
> |
* share GC bookkeeping (especially cardmarks) such that |
602 |
> |
* per-write accesses encounter serious memory contention. |
603 |
|
*/ |
604 |
< |
static final int INITIAL_QUEUE_CAPACITY = 1 << 8; |
604 |
> |
static final int INITIAL_QUEUE_CAPACITY = 1 << 13; |
605 |
|
|
606 |
|
/** |
607 |
|
* Maximum size for queue arrays. Must be a power of two less |
625 |
|
volatile int base; // index of next slot for poll |
626 |
|
int top; // index of next slot for push |
627 |
|
ForkJoinTask<?>[] array; // the elements (initially unallocated) |
628 |
+ |
final ForkJoinPool pool; // the containing pool (may be null) |
629 |
|
final ForkJoinWorkerThread owner; // owning thread or null if shared |
630 |
|
volatile Thread parker; // == owner during call to park; else null |
631 |
< |
ForkJoinTask<?> currentJoin; // task being joined in awaitJoin |
631 |
> |
volatile ForkJoinTask<?> currentJoin; // task being joined in awaitJoin |
632 |
|
ForkJoinTask<?> currentSteal; // current non-local task being executed |
633 |
|
// Heuristic padding to ameliorate unfortunate memory placements |
634 |
< |
Object p00, p01, p02, p03, p04, p05, p06, p07, p08, p09, p0a; |
634 |
> |
Object p00, p01, p02, p03, p04, p05, p06, p07; |
635 |
> |
Object p08, p09, p0a, p0b, p0c, p0d, p0e; |
636 |
|
|
637 |
< |
WorkQueue(ForkJoinWorkerThread owner, int mode) { |
730 |
< |
this.owner = owner; |
637 |
> |
WorkQueue(ForkJoinPool pool, ForkJoinWorkerThread owner, int mode) { |
638 |
|
this.mode = mode; |
639 |
+ |
this.pool = pool; |
640 |
+ |
this.owner = owner; |
641 |
|
// Place indices in the center of array (that is not yet allocated) |
642 |
|
base = top = INITIAL_QUEUE_CAPACITY >>> 1; |
643 |
|
} |
644 |
|
|
645 |
|
/** |
646 |
< |
* Returns number of tasks in the queue. |
646 |
> |
* Returns the approximate number of tasks in the queue. |
647 |
|
*/ |
648 |
|
final int queueSize() { |
649 |
< |
int n = base - top; // non-owner callers must read base first |
650 |
< |
return (n >= 0) ? 0 : -n; |
649 |
> |
int n = base - top; // non-owner callers must read base first |
650 |
> |
return (n >= 0) ? 0 : -n; // ignore transient negative |
651 |
> |
} |
652 |
> |
|
653 |
> |
/** |
654 |
> |
* Provides a more accurate estimate of whether this queue has |
655 |
> |
* any tasks than does queueSize, by checking whether a |
656 |
> |
* near-empty queue has at least one unclaimed task. |
657 |
> |
*/ |
658 |
> |
final boolean isEmpty() { |
659 |
> |
ForkJoinTask<?>[] a; int m, s; |
660 |
> |
int n = base - (s = top); |
661 |
> |
return (n >= 0 || |
662 |
> |
(n == -1 && |
663 |
> |
((a = array) == null || |
664 |
> |
(m = a.length - 1) < 0 || |
665 |
> |
U.getObjectVolatile |
666 |
> |
(a, ((m & (s - 1)) << ASHIFT) + ABASE) == null))); |
667 |
|
} |
668 |
|
|
669 |
|
/** |
670 |
|
* Pushes a task. Call only by owner in unshared queues. |
671 |
|
* |
672 |
|
* @param task the task. Caller must ensure non-null. |
748 |
– |
* @param p if non-null, pool to signal if necessary |
673 |
|
* @throw RejectedExecutionException if array cannot be resized |
674 |
|
*/ |
675 |
< |
final void push(ForkJoinTask<?> task, ForkJoinPool p) { |
676 |
< |
ForkJoinTask<?>[] a; |
675 |
> |
final void push(ForkJoinTask<?> task) { |
676 |
> |
ForkJoinTask<?>[] a; ForkJoinPool p; |
677 |
|
int s = top, m, n; |
678 |
|
if ((a = array) != null) { // ignore if queue removed |
679 |
|
U.putOrderedObject |
680 |
|
(a, (((m = a.length - 1) & s) << ASHIFT) + ABASE, task); |
681 |
|
if ((n = (top = s + 1) - base) <= 2) { |
682 |
< |
if (p != null) |
682 |
> |
if ((p = pool) != null) |
683 |
|
p.signalWork(); |
684 |
|
} |
685 |
|
else if (n >= m) |
698 |
|
boolean submitted = false; |
699 |
|
if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) { |
700 |
|
ForkJoinTask<?>[] a = array; |
701 |
< |
int s = top, n = s - base; |
701 |
> |
int s = top; |
702 |
|
try { |
703 |
< |
if ((a != null && n < a.length - 1) || |
703 |
> |
if ((a != null && a.length > s + 1 - base) || |
704 |
|
(a = growArray(false)) != null) { // must presize |
705 |
|
int j = (((a.length - 1) & s) << ASHIFT) + ABASE; |
706 |
|
U.putObject(a, (long)j, task); // don't need "ordered" |
715 |
|
} |
716 |
|
|
717 |
|
/** |
718 |
< |
* Takes next task, if one exists, in FIFO order. |
718 |
> |
* Takes next task, if one exists, in LIFO order. Call only |
719 |
> |
* by owner in unshared queues. (We do not have a shared |
720 |
> |
* version of this method because it is never needed.) |
721 |
|
*/ |
722 |
< |
final ForkJoinTask<?> poll() { |
723 |
< |
ForkJoinTask<?>[] a; int b, i; |
724 |
< |
while ((b = base) - top < 0 && (a = array) != null && |
725 |
< |
(i = (a.length - 1) & b) >= 0) { |
726 |
< |
int j = (i << ASHIFT) + ABASE; |
727 |
< |
ForkJoinTask<?> t = (ForkJoinTask<?>)U.getObjectVolatile(a, j); |
728 |
< |
if (t != null && base == b && |
722 |
> |
final ForkJoinTask<?> pop() { |
723 |
> |
ForkJoinTask<?>[] a; ForkJoinTask<?> t; int m; |
724 |
> |
if ((a = array) != null && (m = a.length - 1) >= 0) { |
725 |
> |
for (int s; (s = top - 1) - base >= 0;) { |
726 |
> |
long j = ((m & s) << ASHIFT) + ABASE; |
727 |
> |
if ((t = (ForkJoinTask<?>)U.getObject(a, j)) == null) |
728 |
> |
break; |
729 |
> |
if (U.compareAndSwapObject(a, j, t, null)) { |
730 |
> |
top = s; |
731 |
> |
return t; |
732 |
> |
} |
733 |
> |
} |
734 |
> |
} |
735 |
> |
return null; |
736 |
> |
} |
737 |
> |
|
738 |
> |
/** |
739 |
> |
* Takes a task in FIFO order if b is base of queue and a task |
740 |
> |
* can be claimed without contention. Specialized versions |
741 |
> |
* appear in ForkJoinPool methods scan and tryHelpStealer. |
742 |
> |
*/ |
743 |
> |
final ForkJoinTask<?> pollAt(int b) { |
744 |
> |
ForkJoinTask<?> t; ForkJoinTask<?>[] a; |
745 |
> |
if ((a = array) != null) { |
746 |
> |
int j = (((a.length - 1) & b) << ASHIFT) + ABASE; |
747 |
> |
if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) != null && |
748 |
> |
base == b && |
749 |
|
U.compareAndSwapObject(a, j, t, null)) { |
750 |
|
base = b + 1; |
751 |
|
return t; |
755 |
|
} |
756 |
|
|
757 |
|
/** |
758 |
< |
* Takes next task, if one exists, in LIFO order. |
813 |
< |
* Call only by owner in unshared queues. |
758 |
> |
* Takes next task, if one exists, in FIFO order. |
759 |
|
*/ |
760 |
< |
final ForkJoinTask<?> pop() { |
761 |
< |
ForkJoinTask<?> t; int m; |
762 |
< |
ForkJoinTask<?>[] a = array; |
763 |
< |
if (a != null && (m = a.length - 1) >= 0) { |
764 |
< |
for (int s; (s = top - 1) - base >= 0;) { |
765 |
< |
int j = ((m & s) << ASHIFT) + ABASE; |
766 |
< |
if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) == null) |
767 |
< |
break; |
768 |
< |
if (U.compareAndSwapObject(a, j, t, null)) { |
824 |
< |
top = s; |
760 |
> |
final ForkJoinTask<?> poll() { |
761 |
> |
ForkJoinTask<?>[] a; int b; ForkJoinTask<?> t; |
762 |
> |
while ((b = base) - top < 0 && (a = array) != null) { |
763 |
> |
int j = (((a.length - 1) & b) << ASHIFT) + ABASE; |
764 |
> |
t = (ForkJoinTask<?>)U.getObjectVolatile(a, j); |
765 |
> |
if (t != null) { |
766 |
> |
if (base == b && |
767 |
> |
U.compareAndSwapObject(a, j, t, null)) { |
768 |
> |
base = b + 1; |
769 |
|
return t; |
770 |
|
} |
771 |
|
} |
772 |
+ |
else if (base == b) { |
773 |
+ |
if (b + 1 == top) |
774 |
+ |
break; |
775 |
+ |
Thread.yield(); // wait for lagging update |
776 |
+ |
} |
777 |
|
} |
778 |
|
return null; |
779 |
|
} |
798 |
|
} |
799 |
|
|
800 |
|
/** |
852 |
– |
* Returns task at index b if b is current base of queue. |
853 |
– |
*/ |
854 |
– |
final ForkJoinTask<?> pollAt(int b) { |
855 |
– |
ForkJoinTask<?>[] a; int i; |
856 |
– |
ForkJoinTask<?> task = null; |
857 |
– |
if ((a = array) != null && (i = ((a.length - 1) & b)) >= 0) { |
858 |
– |
int j = (i << ASHIFT) + ABASE; |
859 |
– |
ForkJoinTask<?> t = (ForkJoinTask<?>)U.getObjectVolatile(a, j); |
860 |
– |
if (t != null && base == b && |
861 |
– |
U.compareAndSwapObject(a, j, t, null)) { |
862 |
– |
base = b + 1; |
863 |
– |
task = t; |
864 |
– |
} |
865 |
– |
} |
866 |
– |
return task; |
867 |
– |
} |
868 |
– |
|
869 |
– |
/** |
801 |
|
* Pops the given task only if it is at the current top. |
802 |
|
*/ |
803 |
|
final boolean tryUnpush(ForkJoinTask<?> t) { |
812 |
|
} |
813 |
|
|
814 |
|
/** |
815 |
+ |
* Version of tryUnpush for shared queues; called by non-FJ |
816 |
+ |
* submitters. Conservatively fails to unpush if all workers |
817 |
+ |
* are active unless there are multiple tasks in queue. |
818 |
+ |
*/ |
819 |
+ |
final boolean trySharedUnpush(ForkJoinTask<?> task, ForkJoinPool p) { |
820 |
+ |
boolean success = false; |
821 |
+ |
if (task != null && top != base && runState == 0 && |
822 |
+ |
U.compareAndSwapInt(this, RUNSTATE, 0, 1)) { |
823 |
+ |
try { |
824 |
+ |
ForkJoinTask<?>[] a; int n, s; |
825 |
+ |
if ((a = array) != null && (n = (s = top) - base) > 0 && |
826 |
+ |
(n > 1 || p == null || (int)(p.ctl >> AC_SHIFT) < 0)) { |
827 |
+ |
int j = (((a.length - 1) & --s) << ASHIFT) + ABASE; |
828 |
+ |
if (U.getObjectVolatile(a, j) == task && |
829 |
+ |
U.compareAndSwapObject(a, j, task, null)) { |
830 |
+ |
top = s; |
831 |
+ |
success = true; |
832 |
+ |
} |
833 |
+ |
} |
834 |
+ |
} finally { |
835 |
+ |
runState = 0; // unlock |
836 |
+ |
} |
837 |
+ |
} |
838 |
+ |
return success; |
839 |
+ |
} |
840 |
+ |
|
841 |
+ |
/** |
842 |
|
* Polls the given task only if it is at the current base. |
843 |
|
*/ |
844 |
|
final boolean pollFor(ForkJoinTask<?> task) { |
845 |
< |
ForkJoinTask<?>[] a; int b, i; |
846 |
< |
if ((b = base) - top < 0 && (a = array) != null && |
847 |
< |
(i = (a.length - 1) & b) >= 0) { |
890 |
< |
int j = (i << ASHIFT) + ABASE; |
845 |
> |
ForkJoinTask<?>[] a; int b; |
846 |
> |
if ((b = base) - top < 0 && (a = array) != null) { |
847 |
> |
int j = (((a.length - 1) & b) << ASHIFT) + ABASE; |
848 |
|
if (U.getObjectVolatile(a, j) == task && base == b && |
849 |
|
U.compareAndSwapObject(a, j, task, null)) { |
850 |
|
base = b + 1; |
855 |
|
} |
856 |
|
|
857 |
|
/** |
901 |
– |
* If present, removes from queue and executes the given task, or |
902 |
– |
* any other cancelled task. Returns (true) immediately on any CAS |
903 |
– |
* or consistency check failure so caller can retry. |
904 |
– |
* |
905 |
– |
* @return false if no progress can be made |
906 |
– |
*/ |
907 |
– |
final boolean tryRemoveAndExec(ForkJoinTask<?> task) { |
908 |
– |
boolean removed = false, empty = true, progress = true; |
909 |
– |
ForkJoinTask<?>[] a; int m, s, b, n; |
910 |
– |
if ((a = array) != null && (m = a.length - 1) >= 0 && |
911 |
– |
(n = (s = top) - (b = base)) > 0) { |
912 |
– |
for (ForkJoinTask<?> t;;) { // traverse from s to b |
913 |
– |
int j = ((--s & m) << ASHIFT) + ABASE; |
914 |
– |
t = (ForkJoinTask<?>)U.getObjectVolatile(a, j); |
915 |
– |
if (t == null) // inconsistent length |
916 |
– |
break; |
917 |
– |
else if (t == task) { |
918 |
– |
if (s + 1 == top) { // pop |
919 |
– |
if (!U.compareAndSwapObject(a, j, task, null)) |
920 |
– |
break; |
921 |
– |
top = s; |
922 |
– |
removed = true; |
923 |
– |
} |
924 |
– |
else if (base == b) // replace with proxy |
925 |
– |
removed = U.compareAndSwapObject(a, j, task, |
926 |
– |
new EmptyTask()); |
927 |
– |
break; |
928 |
– |
} |
929 |
– |
else if (t.status >= 0) |
930 |
– |
empty = false; |
931 |
– |
else if (s + 1 == top) { // pop and throw away |
932 |
– |
if (U.compareAndSwapObject(a, j, t, null)) |
933 |
– |
top = s; |
934 |
– |
break; |
935 |
– |
} |
936 |
– |
if (--n == 0) { |
937 |
– |
if (!empty && base == b) |
938 |
– |
progress = false; |
939 |
– |
break; |
940 |
– |
} |
941 |
– |
} |
942 |
– |
} |
943 |
– |
if (removed) |
944 |
– |
task.doExec(); |
945 |
– |
return progress; |
946 |
– |
} |
947 |
– |
|
948 |
– |
/** |
858 |
|
* Initializes or doubles the capacity of array. Call either |
859 |
|
* by owner or with lock held -- it is OK for base, but not |
860 |
|
* top, to move while resizings are in progress. |
899 |
|
ForkJoinTask.cancelIgnoringExceptions(t); |
900 |
|
} |
901 |
|
|
902 |
+ |
/** |
903 |
+ |
* Computes next value for random probes. Scans don't require |
904 |
+ |
* a very high quality generator, but also not a crummy one. |
905 |
+ |
* Marsaglia xor-shift is cheap and works well enough. Note: |
906 |
+ |
* This is manually inlined in its usages in ForkJoinPool to |
907 |
+ |
* avoid writes inside busy scan loops. |
908 |
+ |
*/ |
909 |
+ |
final int nextSeed() { |
910 |
+ |
int r = seed; |
911 |
+ |
r ^= r << 13; |
912 |
+ |
r ^= r >>> 17; |
913 |
+ |
return seed = r ^= r << 5; |
914 |
+ |
} |
915 |
+ |
|
916 |
|
// Execution methods |
917 |
|
|
918 |
|
/** |
919 |
< |
* Removes and runs tasks until empty, using local mode |
997 |
< |
* ordering. |
919 |
> |
* Pops and runs tasks until empty. |
920 |
|
*/ |
921 |
< |
final void runLocalTasks() { |
922 |
< |
if (base - top < 0) { |
923 |
< |
for (ForkJoinTask<?> t; (t = nextLocalTask()) != null; ) |
921 |
> |
private void popAndExecAll() { |
922 |
> |
// A bit faster than repeated pop calls |
923 |
> |
ForkJoinTask<?>[] a; int m, s; long j; ForkJoinTask<?> t; |
924 |
> |
while ((a = array) != null && (m = a.length - 1) >= 0 && |
925 |
> |
(s = top - 1) - base >= 0 && |
926 |
> |
(t = ((ForkJoinTask<?>) |
927 |
> |
U.getObject(a, j = ((m & s) << ASHIFT) + ABASE))) |
928 |
> |
!= null) { |
929 |
> |
if (U.compareAndSwapObject(a, j, t, null)) { |
930 |
> |
top = s; |
931 |
|
t.doExec(); |
932 |
+ |
} |
933 |
+ |
} |
934 |
+ |
} |
935 |
+ |
|
936 |
+ |
/** |
937 |
+ |
* Polls and runs tasks until empty. |
938 |
+ |
*/ |
939 |
+ |
private void pollAndExecAll() { |
940 |
+ |
for (ForkJoinTask<?> t; (t = poll()) != null;) |
941 |
+ |
t.doExec(); |
942 |
+ |
} |
943 |
+ |
|
944 |
+ |
/** |
945 |
+ |
* If present, removes from queue and executes the given task, or |
946 |
+ |
* any other cancelled task. Returns (true) immediately on any CAS |
947 |
+ |
* or consistency check failure so caller can retry. |
948 |
+ |
* |
949 |
+ |
* @return 0 if no progress can be made, else positive |
950 |
+ |
* (this unusual convention simplifies use with tryHelpStealer.) |
951 |
+ |
*/ |
952 |
+ |
final int tryRemoveAndExec(ForkJoinTask<?> task) { |
953 |
+ |
int stat = 1; |
954 |
+ |
boolean removed = false, empty = true; |
955 |
+ |
ForkJoinTask<?>[] a; int m, s, b, n; |
956 |
+ |
if ((a = array) != null && (m = a.length - 1) >= 0 && |
957 |
+ |
(n = (s = top) - (b = base)) > 0) { |
958 |
+ |
for (ForkJoinTask<?> t;;) { // traverse from s to b |
959 |
+ |
int j = ((--s & m) << ASHIFT) + ABASE; |
960 |
+ |
t = (ForkJoinTask<?>)U.getObjectVolatile(a, j); |
961 |
+ |
if (t == null) // inconsistent length |
962 |
+ |
break; |
963 |
+ |
else if (t == task) { |
964 |
+ |
if (s + 1 == top) { // pop |
965 |
+ |
if (!U.compareAndSwapObject(a, j, task, null)) |
966 |
+ |
break; |
967 |
+ |
top = s; |
968 |
+ |
removed = true; |
969 |
+ |
} |
970 |
+ |
else if (base == b) // replace with proxy |
971 |
+ |
removed = U.compareAndSwapObject(a, j, task, |
972 |
+ |
new EmptyTask()); |
973 |
+ |
break; |
974 |
+ |
} |
975 |
+ |
else if (t.status >= 0) |
976 |
+ |
empty = false; |
977 |
+ |
else if (s + 1 == top) { // pop and throw away |
978 |
+ |
if (U.compareAndSwapObject(a, j, t, null)) |
979 |
+ |
top = s; |
980 |
+ |
break; |
981 |
+ |
} |
982 |
+ |
if (--n == 0) { |
983 |
+ |
if (!empty && base == b) |
984 |
+ |
stat = 0; |
985 |
+ |
break; |
986 |
+ |
} |
987 |
+ |
} |
988 |
|
} |
989 |
+ |
if (removed) |
990 |
+ |
task.doExec(); |
991 |
+ |
return stat; |
992 |
|
} |
993 |
|
|
994 |
|
/** |
995 |
|
* Executes a top-level task and any local tasks remaining |
996 |
|
* after execution. |
1009 |
– |
* |
1010 |
– |
* @return true unless terminating |
997 |
|
*/ |
998 |
< |
final boolean runTask(ForkJoinTask<?> t) { |
1013 |
< |
boolean alive = true; |
998 |
> |
final void runTask(ForkJoinTask<?> t) { |
999 |
|
if (t != null) { |
1000 |
|
currentSteal = t; |
1001 |
|
t.doExec(); |
1002 |
< |
runLocalTasks(); |
1002 |
> |
if (top != base) { // process remaining local tasks |
1003 |
> |
if (mode == 0) |
1004 |
> |
popAndExecAll(); |
1005 |
> |
else |
1006 |
> |
pollAndExecAll(); |
1007 |
> |
} |
1008 |
|
++nsteals; |
1009 |
|
currentSteal = null; |
1010 |
|
} |
1021 |
– |
else if (runState < 0) // terminating |
1022 |
– |
alive = false; |
1023 |
– |
return alive; |
1011 |
|
} |
1012 |
|
|
1013 |
|
/** |
1023 |
|
} |
1024 |
|
|
1025 |
|
/** |
1026 |
< |
* Computes next value for random probes. Scans don't require |
1040 |
< |
* a very high quality generator, but also not a crummy one. |
1041 |
< |
* Marsaglia xor-shift is cheap and works well enough. Note: |
1042 |
< |
* This is manually inlined in several usages in ForkJoinPool |
1043 |
< |
* to avoid writes inside busy scan loops. |
1026 |
> |
* Returns true if owned and not known to be blocked. |
1027 |
|
*/ |
1028 |
< |
final int nextSeed() { |
1029 |
< |
int r = seed; |
1030 |
< |
r ^= r << 13; |
1031 |
< |
r ^= r >>> 17; |
1032 |
< |
r ^= r << 5; |
1033 |
< |
return seed = r; |
1028 |
> |
final boolean isApparentlyUnblocked() { |
1029 |
> |
Thread wt; Thread.State s; |
1030 |
> |
return (eventCount >= 0 && |
1031 |
> |
(wt = owner) != null && |
1032 |
> |
(s = wt.getState()) != Thread.State.BLOCKED && |
1033 |
> |
s != Thread.State.WAITING && |
1034 |
> |
s != Thread.State.TIMED_WAITING); |
1035 |
> |
} |
1036 |
> |
|
1037 |
> |
/** |
1038 |
> |
* If this owned and is not already interrupted, try to |
1039 |
> |
* interrupt and/or unpark, ignoring exceptions. |
1040 |
> |
*/ |
1041 |
> |
final void interruptOwner() { |
1042 |
> |
Thread wt, p; |
1043 |
> |
if ((wt = owner) != null && !wt.isInterrupted()) { |
1044 |
> |
try { |
1045 |
> |
wt.interrupt(); |
1046 |
> |
} catch (SecurityException ignore) { |
1047 |
> |
} |
1048 |
> |
} |
1049 |
> |
if ((p = parker) != null) |
1050 |
> |
U.unpark(p); |
1051 |
|
} |
1052 |
|
|
1053 |
|
// Unsafe mechanics |
1075 |
|
} |
1076 |
|
|
1077 |
|
/** |
1078 |
< |
* Class for artificial tasks that are used to replace the target |
1079 |
< |
* of local joins if they are removed from an interior queue slot |
1080 |
< |
* in WorkQueue.tryRemoveAndExec. We don't need the proxy to |
1081 |
< |
* actually do anything beyond having a unique identity. |
1082 |
< |
*/ |
1083 |
< |
static final class EmptyTask extends ForkJoinTask<Void> { |
1084 |
< |
EmptyTask() { status = ForkJoinTask.NORMAL; } // force done |
1085 |
< |
public Void getRawResult() { return null; } |
1086 |
< |
public void setRawResult(Void x) {} |
1087 |
< |
public boolean exec() { return true; } |
1088 |
< |
} |
1089 |
< |
|
1090 |
< |
/** |
1091 |
< |
* Per-thread records for (typically non-FJ) threads that submit |
1092 |
< |
* to pools. Cureently holds only psuedo-random seed / index that |
1093 |
< |
* is used to choose submission queues in method doSubmit. In the |
1094 |
< |
* future, this may incorporate a means to implement different |
1095 |
< |
* task rejection and resubmission policies. |
1078 |
> |
* Per-thread records for threads that submit to pools. Currently |
1079 |
> |
* holds only pseudo-random seed / index that is used to choose |
1080 |
> |
* submission queues in method doSubmit. In the future, this may |
1081 |
> |
* also incorporate a means to implement different task rejection |
1082 |
> |
* and resubmission policies. |
1083 |
> |
* |
1084 |
> |
* Seeds for submitters and workers/workQueues work in basically |
1085 |
> |
* the same way but are initialized and updated using slightly |
1086 |
> |
* different mechanics. Both are initialized using the same |
1087 |
> |
* approach as in class ThreadLocal, where successive values are |
1088 |
> |
* unlikely to collide with previous values. This is done during |
1089 |
> |
* registration for workers, but requires a separate AtomicInteger |
1090 |
> |
* for submitters. Seeds are then randomly modified upon |
1091 |
> |
* collisions using xorshifts, which requires a non-zero seed. |
1092 |
|
*/ |
1093 |
|
static final class Submitter { |
1094 |
< |
int seed; // seed for random submission queue selection |
1099 |
< |
|
1100 |
< |
// Heuristic padding to ameliorate unfortunate memory placements |
1101 |
< |
int p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, pa, pb, pc, pd, pe; |
1102 |
< |
|
1094 |
> |
int seed; |
1095 |
|
Submitter() { |
1096 |
< |
// Use identityHashCode, forced negative, for seed |
1097 |
< |
seed = System.identityHashCode(Thread.currentThread()) | (1 << 31); |
1106 |
< |
} |
1107 |
< |
|
1108 |
< |
/** |
1109 |
< |
* Computes next value for random probes. Like method |
1110 |
< |
* WorkQueue.nextSeed, this is manually inlined in several |
1111 |
< |
* usages to avoid writes inside busy loops. |
1112 |
< |
*/ |
1113 |
< |
final int nextSeed() { |
1114 |
< |
int r = seed; |
1115 |
< |
r ^= r << 13; |
1116 |
< |
r ^= r >>> 17; |
1117 |
< |
return seed = r ^= r << 5; |
1096 |
> |
int s = nextSubmitterSeed.getAndAdd(SEED_INCREMENT); |
1097 |
> |
seed = (s == 0) ? 1 : s; // ensure non-zero |
1098 |
|
} |
1099 |
|
} |
1100 |
|
|
1103 |
|
public Submitter initialValue() { return new Submitter(); } |
1104 |
|
} |
1105 |
|
|
1106 |
+ |
// static fields (initialized in static initializer below) |
1107 |
+ |
|
1108 |
|
/** |
1109 |
< |
* Per-thread submission bookeeping. Shared across all pools |
1109 |
> |
* Creates a new ForkJoinWorkerThread. This factory is used unless |
1110 |
> |
* overridden in ForkJoinPool constructors. |
1111 |
> |
*/ |
1112 |
> |
public static final ForkJoinWorkerThreadFactory |
1113 |
> |
defaultForkJoinWorkerThreadFactory; |
1114 |
> |
|
1115 |
> |
/** |
1116 |
> |
* Generator for assigning sequence numbers as pool names. |
1117 |
> |
*/ |
1118 |
> |
private static final AtomicInteger poolNumberGenerator; |
1119 |
> |
|
1120 |
> |
/** |
1121 |
> |
* Generator for initial hashes/seeds for submitters. Accessed by |
1122 |
> |
* Submitter class constructor. |
1123 |
> |
*/ |
1124 |
> |
static final AtomicInteger nextSubmitterSeed; |
1125 |
> |
|
1126 |
> |
/** |
1127 |
> |
* Permission required for callers of methods that may start or |
1128 |
> |
* kill threads. |
1129 |
> |
*/ |
1130 |
> |
private static final RuntimePermission modifyThreadPermission; |
1131 |
> |
|
1132 |
> |
/** |
1133 |
> |
* Per-thread submission bookkeeping. Shared across all pools |
1134 |
|
* to reduce ThreadLocal pollution and because random motion |
1135 |
|
* to avoid contention in one pool is likely to hold for others. |
1136 |
|
*/ |
1137 |
< |
static final ThreadSubmitter submitters = new ThreadSubmitter(); |
1137 |
> |
private static final ThreadSubmitter submitters; |
1138 |
> |
|
1139 |
> |
/** Common default pool */ |
1140 |
> |
static volatile ForkJoinPool commonPool; |
1141 |
> |
|
1142 |
> |
// commonPool construction parameters |
1143 |
> |
private static final String propPrefix = |
1144 |
> |
"java.util.concurrent.ForkJoinPool.common."; |
1145 |
> |
private static final Thread.UncaughtExceptionHandler commonPoolUEH; |
1146 |
> |
private static final ForkJoinWorkerThreadFactory commonPoolFactory; |
1147 |
> |
static final int commonPoolParallelism; |
1148 |
> |
|
1149 |
> |
/** Static initialization lock */ |
1150 |
> |
private static final Mutex initializationLock; |
1151 |
> |
|
1152 |
> |
// static constants |
1153 |
|
|
1154 |
|
/** |
1155 |
< |
* Top-level runloop for workers |
1155 |
> |
* Initial timeout value (in nanoseconds) for the tread triggering |
1156 |
> |
* quiescence to park waiting for new work. On timeout, the thread |
1157 |
> |
* will instead try to shrink the number of workers. |
1158 |
|
*/ |
1159 |
< |
final void runWorker(ForkJoinWorkerThread wt) { |
1137 |
< |
// Initialize queue array and seed in this thread |
1138 |
< |
WorkQueue w = wt.workQueue; |
1139 |
< |
w.growArray(false); |
1140 |
< |
// Same initial hash as Submitters |
1141 |
< |
w.seed = System.identityHashCode(Thread.currentThread()) | (1 << 31); |
1159 |
> |
private static final long IDLE_TIMEOUT = 1000L * 1000L * 1000L; // 1sec |
1160 |
|
|
1161 |
< |
do {} while (w.runTask(scan(w))); |
1162 |
< |
} |
1161 |
> |
/** |
1162 |
> |
* Timeout value when there are more threads than parallelism level |
1163 |
> |
*/ |
1164 |
> |
private static final long FAST_IDLE_TIMEOUT = 100L * 1000L * 1000L; |
1165 |
> |
|
1166 |
> |
/** |
1167 |
> |
* The maximum stolen->joining link depth allowed in method |
1168 |
> |
* tryHelpStealer. Must be a power of two. This value also |
1169 |
> |
* controls the maximum number of times to try to help join a task |
1170 |
> |
* without any apparent progress or change in pool state before |
1171 |
> |
* giving up and blocking (see awaitJoin). Depths for legitimate |
1172 |
> |
* chains are unbounded, but we use a fixed constant to avoid |
1173 |
> |
* (otherwise unchecked) cycles and to bound staleness of |
1174 |
> |
* traversal parameters at the expense of sometimes blocking when |
1175 |
> |
* we could be helping. |
1176 |
> |
*/ |
1177 |
> |
private static final int MAX_HELP = 64; |
1178 |
> |
|
1179 |
> |
/** |
1180 |
> |
* Secondary time-based bound (in nanosecs) for helping attempts |
1181 |
> |
* before trying compensated blocking in awaitJoin. Used in |
1182 |
> |
* conjunction with MAX_HELP to reduce variance due to different |
1183 |
> |
* polling rates associated with different helping options. The |
1184 |
> |
* value should roughly approximate the time required to create |
1185 |
> |
* and/or activate a worker thread. |
1186 |
> |
*/ |
1187 |
> |
private static final long COMPENSATION_DELAY = 1L << 18; // ~0.25 millisec |
1188 |
> |
|
1189 |
> |
/** |
1190 |
> |
* Increment for seed generators. See class ThreadLocal for |
1191 |
> |
* explanation. |
1192 |
> |
*/ |
1193 |
> |
private static final int SEED_INCREMENT = 0x61c88647; |
1194 |
> |
|
1195 |
> |
/** |
1196 |
> |
* Bits and masks for control variables |
1197 |
> |
* |
1198 |
> |
* Field ctl is a long packed with: |
1199 |
> |
* AC: Number of active running workers minus target parallelism (16 bits) |
1200 |
> |
* TC: Number of total workers minus target parallelism (16 bits) |
1201 |
> |
* ST: true if pool is terminating (1 bit) |
1202 |
> |
* EC: the wait count of top waiting thread (15 bits) |
1203 |
> |
* ID: poolIndex of top of Treiber stack of waiters (16 bits) |
1204 |
> |
* |
1205 |
> |
* When convenient, we can extract the upper 32 bits of counts and |
1206 |
> |
* the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e = |
1207 |
> |
* (int)ctl. The ec field is never accessed alone, but always |
1208 |
> |
* together with id and st. The offsets of counts by the target |
1209 |
> |
* parallelism and the positionings of fields makes it possible to |
1210 |
> |
* perform the most common checks via sign tests of fields: When |
1211 |
> |
* ac is negative, there are not enough active workers, when tc is |
1212 |
> |
* negative, there are not enough total workers, and when e is |
1213 |
> |
* negative, the pool is terminating. To deal with these possibly |
1214 |
> |
* negative fields, we use casts in and out of "short" and/or |
1215 |
> |
* signed shifts to maintain signedness. |
1216 |
> |
* |
1217 |
> |
* When a thread is queued (inactivated), its eventCount field is |
1218 |
> |
* set negative, which is the only way to tell if a worker is |
1219 |
> |
* prevented from executing tasks, even though it must continue to |
1220 |
> |
* scan for them to avoid queuing races. Note however that |
1221 |
> |
* eventCount updates lag releases so usage requires care. |
1222 |
> |
* |
1223 |
> |
* Field runState is an int packed with: |
1224 |
> |
* SHUTDOWN: true if shutdown is enabled (1 bit) |
1225 |
> |
* SEQ: a sequence number updated upon (de)registering workers (30 bits) |
1226 |
> |
* INIT: set true after workQueues array construction (1 bit) |
1227 |
> |
* |
1228 |
> |
* The sequence number enables simple consistency checks: |
1229 |
> |
* Staleness of read-only operations on the workQueues array can |
1230 |
> |
* be checked by comparing runState before vs after the reads. |
1231 |
> |
*/ |
1232 |
> |
|
1233 |
> |
// bit positions/shifts for fields |
1234 |
> |
private static final int AC_SHIFT = 48; |
1235 |
> |
private static final int TC_SHIFT = 32; |
1236 |
> |
private static final int ST_SHIFT = 31; |
1237 |
> |
private static final int EC_SHIFT = 16; |
1238 |
> |
|
1239 |
> |
// bounds |
1240 |
> |
private static final int SMASK = 0xffff; // short bits |
1241 |
> |
private static final int MAX_CAP = 0x7fff; // max #workers - 1 |
1242 |
> |
private static final int SQMASK = 0xfffe; // even short bits |
1243 |
> |
private static final int SHORT_SIGN = 1 << 15; |
1244 |
> |
private static final int INT_SIGN = 1 << 31; |
1245 |
> |
|
1246 |
> |
// masks |
1247 |
> |
private static final long STOP_BIT = 0x0001L << ST_SHIFT; |
1248 |
> |
private static final long AC_MASK = ((long)SMASK) << AC_SHIFT; |
1249 |
> |
private static final long TC_MASK = ((long)SMASK) << TC_SHIFT; |
1250 |
> |
|
1251 |
> |
// units for incrementing and decrementing |
1252 |
> |
private static final long TC_UNIT = 1L << TC_SHIFT; |
1253 |
> |
private static final long AC_UNIT = 1L << AC_SHIFT; |
1254 |
> |
|
1255 |
> |
// masks and units for dealing with u = (int)(ctl >>> 32) |
1256 |
> |
private static final int UAC_SHIFT = AC_SHIFT - 32; |
1257 |
> |
private static final int UTC_SHIFT = TC_SHIFT - 32; |
1258 |
> |
private static final int UAC_MASK = SMASK << UAC_SHIFT; |
1259 |
> |
private static final int UTC_MASK = SMASK << UTC_SHIFT; |
1260 |
> |
private static final int UAC_UNIT = 1 << UAC_SHIFT; |
1261 |
> |
private static final int UTC_UNIT = 1 << UTC_SHIFT; |
1262 |
> |
|
1263 |
> |
// masks and units for dealing with e = (int)ctl |
1264 |
> |
private static final int E_MASK = 0x7fffffff; // no STOP_BIT |
1265 |
> |
private static final int E_SEQ = 1 << EC_SHIFT; |
1266 |
> |
|
1267 |
> |
// runState bits |
1268 |
> |
private static final int SHUTDOWN = 1 << 31; |
1269 |
> |
|
1270 |
> |
// access mode for WorkQueue |
1271 |
> |
static final int LIFO_QUEUE = 0; |
1272 |
> |
static final int FIFO_QUEUE = 1; |
1273 |
> |
static final int SHARED_QUEUE = -1; |
1274 |
> |
|
1275 |
> |
// Instance fields |
1276 |
> |
|
1277 |
> |
/* |
1278 |
> |
* Field layout order in this class tends to matter more than one |
1279 |
> |
* would like. Runtime layout order is only loosely related to |
1280 |
> |
* declaration order and may differ across JVMs, but the following |
1281 |
> |
* empirically works OK on current JVMs. |
1282 |
> |
*/ |
1283 |
|
|
1284 |
< |
// Creating, registering and deregistering workers |
1284 |
> |
volatile long ctl; // main pool control |
1285 |
> |
final int parallelism; // parallelism level |
1286 |
> |
final int localMode; // per-worker scheduling mode |
1287 |
> |
final int submitMask; // submit queue index bound |
1288 |
> |
int nextSeed; // for initializing worker seeds |
1289 |
> |
volatile int runState; // shutdown status and seq |
1290 |
> |
WorkQueue[] workQueues; // main registry |
1291 |
> |
final Mutex lock; // for registration |
1292 |
> |
final Condition termination; // for awaitTermination |
1293 |
> |
final ForkJoinWorkerThreadFactory factory; // factory for new workers |
1294 |
> |
final Thread.UncaughtExceptionHandler ueh; // per-worker UEH |
1295 |
> |
final AtomicLong stealCount; // collect counts when terminated |
1296 |
> |
final AtomicInteger nextWorkerNumber; // to create worker name string |
1297 |
> |
String workerNamePrefix; // to create worker name string |
1298 |
> |
|
1299 |
> |
// Creating, registering, and deregistering workers |
1300 |
|
|
1301 |
|
/** |
1302 |
|
* Tries to create and start a worker |
1303 |
|
*/ |
1304 |
|
private void addWorker() { |
1305 |
|
Throwable ex = null; |
1306 |
< |
ForkJoinWorkerThread w = null; |
1306 |
> |
ForkJoinWorkerThread wt = null; |
1307 |
|
try { |
1308 |
< |
if ((w = factory.newThread(this)) != null) { |
1309 |
< |
w.start(); |
1308 |
> |
if ((wt = factory.newThread(this)) != null) { |
1309 |
> |
wt.start(); |
1310 |
|
return; |
1311 |
|
} |
1312 |
|
} catch (Throwable e) { |
1313 |
|
ex = e; |
1314 |
|
} |
1315 |
< |
deregisterWorker(w, ex); |
1315 |
> |
deregisterWorker(wt, ex); // adjust counts etc on failure |
1316 |
|
} |
1317 |
|
|
1318 |
|
/** |
1327 |
|
} |
1328 |
|
|
1329 |
|
/** |
1330 |
< |
* Callback from ForkJoinWorkerThread constructor to establish and |
1331 |
< |
* record its WorkQueue. |
1330 |
> |
* Callback from ForkJoinWorkerThread constructor to establish its |
1331 |
> |
* poolIndex and record its WorkQueue. To avoid scanning bias due |
1332 |
> |
* to packing entries in front of the workQueues array, we treat |
1333 |
> |
* the array as a simple power-of-two hash table using per-thread |
1334 |
> |
* seed as hash, expanding as needed. |
1335 |
|
* |
1336 |
< |
* @param wt the worker thread |
1336 |
> |
* @param w the worker's queue |
1337 |
|
*/ |
1338 |
< |
final void registerWorker(ForkJoinWorkerThread wt) { |
1339 |
< |
WorkQueue w = wt.workQueue; |
1184 |
< |
ReentrantLock lock = this.lock; |
1338 |
> |
final void registerWorker(WorkQueue w) { |
1339 |
> |
Mutex lock = this.lock; |
1340 |
|
lock.lock(); |
1341 |
|
try { |
1187 |
– |
int k = nextPoolIndex; |
1342 |
|
WorkQueue[] ws = workQueues; |
1343 |
< |
if (ws != null) { // ignore on shutdown |
1344 |
< |
int n = ws.length; |
1345 |
< |
if (k < 0 || (k & 1) == 0 || k >= n || ws[k] != null) { |
1346 |
< |
for (k = 1; k < n && ws[k] != null; k += 2) |
1347 |
< |
; // workers are at odd indices |
1348 |
< |
if (k >= n) // resize |
1349 |
< |
workQueues = ws = Arrays.copyOf(ws, n << 1); |
1350 |
< |
} |
1351 |
< |
w.poolIndex = k; |
1352 |
< |
w.eventCount = ~(k >>> 1) & SMASK; // Set up wait count |
1353 |
< |
ws[k] = w; // record worker |
1354 |
< |
nextPoolIndex = k + 2; |
1355 |
< |
int rs = runState; |
1356 |
< |
int m = rs & SMASK; // recalculate runState mask |
1357 |
< |
if (k > m) |
1358 |
< |
m = (m << 1) + 1; |
1359 |
< |
runState = (rs & SHUTDOWN) | ((rs + RS_SEQ) & RS_SEQ_MASK) | m; |
1343 |
> |
if (w != null && ws != null) { // skip on shutdown/failure |
1344 |
> |
int rs, n = ws.length, m = n - 1; |
1345 |
> |
int s = nextSeed += SEED_INCREMENT; // rarely-colliding sequence |
1346 |
> |
w.seed = (s == 0) ? 1 : s; // ensure non-zero seed |
1347 |
> |
int r = (s << 1) | 1; // use odd-numbered indices |
1348 |
> |
if (ws[r &= m] != null) { // collision |
1349 |
> |
int probes = 0; // step by approx half size |
1350 |
> |
int step = (n <= 4) ? 2 : ((n >>> 1) & SQMASK) + 2; |
1351 |
> |
while (ws[r = (r + step) & m] != null) { |
1352 |
> |
if (++probes >= n) { |
1353 |
> |
workQueues = ws = Arrays.copyOf(ws, n <<= 1); |
1354 |
> |
m = n - 1; |
1355 |
> |
probes = 0; |
1356 |
> |
} |
1357 |
> |
} |
1358 |
> |
} |
1359 |
> |
w.eventCount = w.poolIndex = r; // establish before recording |
1360 |
> |
ws[r] = w; // also update seq |
1361 |
> |
runState = ((rs = runState) & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN); |
1362 |
|
} |
1363 |
|
} finally { |
1364 |
|
lock.unlock(); |
1366 |
|
} |
1367 |
|
|
1368 |
|
/** |
1369 |
< |
* Final callback from terminating worker, as well as failure to |
1370 |
< |
* construct or start a worker in addWorker. Removes record of |
1369 |
> |
* Final callback from terminating worker, as well as upon failure |
1370 |
> |
* to construct or start a worker in addWorker. Removes record of |
1371 |
|
* worker from array, and adjusts counts. If pool is shutting |
1372 |
|
* down, tries to complete termination. |
1373 |
|
* |
1375 |
|
* @param ex the exception causing failure, or null if none |
1376 |
|
*/ |
1377 |
|
final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) { |
1378 |
+ |
Mutex lock = this.lock; |
1379 |
|
WorkQueue w = null; |
1380 |
|
if (wt != null && (w = wt.workQueue) != null) { |
1381 |
|
w.runState = -1; // ensure runState is set |
1382 |
|
stealCount.getAndAdd(w.totalSteals + w.nsteals); |
1383 |
|
int idx = w.poolIndex; |
1227 |
– |
ReentrantLock lock = this.lock; |
1384 |
|
lock.lock(); |
1385 |
|
try { // remove record from array |
1386 |
|
WorkQueue[] ws = workQueues; |
1387 |
|
if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w) |
1388 |
< |
ws[nextPoolIndex = idx] = null; |
1388 |
> |
ws[idx] = null; |
1389 |
|
} finally { |
1390 |
|
lock.unlock(); |
1391 |
|
} |
1397 |
|
((c - TC_UNIT) & TC_MASK) | |
1398 |
|
(c & ~(AC_MASK|TC_MASK))))); |
1399 |
|
|
1400 |
< |
if (!tryTerminate(false) && w != null) { |
1400 |
> |
if (!tryTerminate(false, false) && w != null) { |
1401 |
|
w.cancelAll(); // cancel remaining tasks |
1402 |
|
if (w.array != null) // suppress signal if never ran |
1403 |
|
signalWork(); // wake up or create replacement |
1404 |
+ |
if (ex == null) // help clean refs on way out |
1405 |
+ |
ForkJoinTask.helpExpungeStaleExceptions(); |
1406 |
|
} |
1407 |
|
|
1408 |
|
if (ex != null) // rethrow |
1409 |
|
U.throwException(ex); |
1410 |
|
} |
1411 |
|
|
1412 |
+ |
// Submissions |
1413 |
+ |
|
1414 |
|
/** |
1415 |
< |
* Tries to add and register a new queue at the given index. |
1415 |
> |
* Unless shutting down, adds the given task to a submission queue |
1416 |
> |
* at submitter's current queue index (modulo submission |
1417 |
> |
* range). If no queue exists at the index, one is created. If |
1418 |
> |
* the queue is busy, another index is randomly chosen. The |
1419 |
> |
* submitMask bounds the effective number of queues to the |
1420 |
> |
* (nearest power of two for) parallelism level. |
1421 |
|
* |
1422 |
< |
* @param idx the workQueues array index to register the queue |
1423 |
< |
* @return the queue, or null if could not add because could |
1424 |
< |
* not acquire lock or idx is unusable |
1425 |
< |
*/ |
1426 |
< |
private WorkQueue tryAddSharedQueue(int idx) { |
1427 |
< |
WorkQueue q = null; |
1428 |
< |
ReentrantLock lock = this.lock; |
1429 |
< |
if (idx >= 0 && (idx & 1) == 0 && !lock.isLocked()) { |
1430 |
< |
// create queue outside of lock but only if apparently free |
1431 |
< |
WorkQueue nq = new WorkQueue(null, SHARED_QUEUE); |
1432 |
< |
if (lock.tryLock()) { |
1433 |
< |
try { |
1434 |
< |
WorkQueue[] ws = workQueues; |
1435 |
< |
if (ws != null && idx < ws.length) { |
1436 |
< |
if ((q = ws[idx]) == null) { |
1437 |
< |
int rs; // update runState seq |
1438 |
< |
ws[idx] = q = nq; |
1439 |
< |
runState = (((rs = runState) & SHUTDOWN) | |
1275 |
< |
((rs + RS_SEQ) & ~SHUTDOWN)); |
1276 |
< |
} |
1422 |
> |
* @param task the task. Caller must ensure non-null. |
1423 |
> |
*/ |
1424 |
> |
private void doSubmit(ForkJoinTask<?> task) { |
1425 |
> |
Submitter s = submitters.get(); |
1426 |
> |
for (int r = s.seed, m = submitMask;;) { |
1427 |
> |
WorkQueue[] ws; WorkQueue q; |
1428 |
> |
int k = r & m & SQMASK; // use only even indices |
1429 |
> |
if (runState < 0 || (ws = workQueues) == null || ws.length <= k) |
1430 |
> |
throw new RejectedExecutionException(); // shutting down |
1431 |
> |
else if ((q = ws[k]) == null) { // create new queue |
1432 |
> |
WorkQueue nq = new WorkQueue(this, null, SHARED_QUEUE); |
1433 |
> |
Mutex lock = this.lock; // construct outside lock |
1434 |
> |
lock.lock(); |
1435 |
> |
try { // recheck under lock |
1436 |
> |
int rs = runState; // to update seq |
1437 |
> |
if (ws == workQueues && ws[k] == null) { |
1438 |
> |
ws[k] = nq; |
1439 |
> |
runState = ((rs & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN)); |
1440 |
|
} |
1441 |
|
} finally { |
1442 |
|
lock.unlock(); |
1443 |
|
} |
1444 |
|
} |
1445 |
+ |
else if (q.trySharedPush(task)) { |
1446 |
+ |
signalWork(); |
1447 |
+ |
return; |
1448 |
+ |
} |
1449 |
+ |
else if (m > 1) { // move to a different index |
1450 |
+ |
r ^= r << 13; // same xorshift as WorkQueues |
1451 |
+ |
r ^= r >>> 17; |
1452 |
+ |
s.seed = r ^= r << 5; |
1453 |
+ |
} |
1454 |
+ |
else |
1455 |
+ |
Thread.yield(); // yield if no alternatives |
1456 |
|
} |
1457 |
< |
return q; |
1457 |
> |
} |
1458 |
> |
|
1459 |
> |
/** |
1460 |
> |
* Submits the given (non-null) task to the common pool, if possible. |
1461 |
> |
*/ |
1462 |
> |
static void submitToCommonPool(ForkJoinTask<?> task) { |
1463 |
> |
ForkJoinPool p; |
1464 |
> |
if ((p = commonPool) == null) |
1465 |
> |
p = ensureCommonPool(); |
1466 |
> |
p.doSubmit(task); |
1467 |
> |
} |
1468 |
> |
|
1469 |
> |
/** |
1470 |
> |
* Returns true if the given task was submitted to common pool |
1471 |
> |
* and has not yet commenced execution, and is available for |
1472 |
> |
* removal according to execution policies; if so removing the |
1473 |
> |
* submission from the pool. |
1474 |
> |
* |
1475 |
> |
* @param task the task |
1476 |
> |
* @return true if successful |
1477 |
> |
*/ |
1478 |
> |
static boolean tryUnsubmitFromCommonPool(ForkJoinTask<?> task) { |
1479 |
> |
ForkJoinPool p; WorkQueue[] ws; WorkQueue q; |
1480 |
> |
int k = submitters.get().seed & SQMASK; |
1481 |
> |
return ((p = commonPool) != null && |
1482 |
> |
(ws = p.workQueues) != null && |
1483 |
> |
ws.length > (k &= p.submitMask) && |
1484 |
> |
(q = ws[k]) != null && |
1485 |
> |
q.trySharedUnpush(task, p)); |
1486 |
|
} |
1487 |
|
|
1488 |
|
// Maintaining ctl counts |
1496 |
|
} |
1497 |
|
|
1498 |
|
/** |
1499 |
< |
* Activates or creates a worker. |
1499 |
> |
* Tries to create one or activate one or more workers if too few are active. |
1500 |
|
*/ |
1501 |
|
final void signalWork() { |
1502 |
< |
/* |
1503 |
< |
* The while condition is true if: (there is are too few total |
1504 |
< |
* workers OR there is at least one waiter) AND (there are too |
1505 |
< |
* few active workers OR the pool is terminating). The value |
1506 |
< |
* of e distinguishes the remaining cases: zero (no waiters) |
1507 |
< |
* for create, negative if terminating (in which case do |
1508 |
< |
* nothing), else release a waiter. The secondary checks for |
1509 |
< |
* release (non-null array etc) can fail if the pool begins |
1510 |
< |
* terminating after the test, and don't impose any added cost |
1511 |
< |
* because JVMs must perform null and bounds checks anyway. |
1512 |
< |
*/ |
1513 |
< |
long c; int e, u; |
1514 |
< |
while ((((e = (int)(c = ctl)) | (u = (int)(c >>> 32))) & |
1515 |
< |
(INT_SIGN|SHORT_SIGN)) == (INT_SIGN|SHORT_SIGN)) { |
1314 |
< |
WorkQueue[] ws = workQueues; int i; WorkQueue w; Thread p; |
1315 |
< |
if (e == 0) { // add a new worker |
1316 |
< |
if (U.compareAndSwapLong |
1317 |
< |
(this, CTL, c, (long)(((u + UTC_UNIT) & UTC_MASK) | |
1318 |
< |
((u + UAC_UNIT) & UAC_MASK)) << 32)) { |
1319 |
< |
addWorker(); |
1320 |
< |
break; |
1502 |
> |
long c; int u; |
1503 |
> |
while ((u = (int)((c = ctl) >>> 32)) < 0) { // too few active |
1504 |
> |
WorkQueue[] ws = workQueues; int e, i; WorkQueue w; Thread p; |
1505 |
> |
if ((e = (int)c) > 0) { // at least one waiting |
1506 |
> |
if (ws != null && (i = e & SMASK) < ws.length && |
1507 |
> |
(w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) { |
1508 |
> |
long nc = (((long)(w.nextWait & E_MASK)) | |
1509 |
> |
((long)(u + UAC_UNIT) << 32)); |
1510 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
1511 |
> |
w.eventCount = (e + E_SEQ) & E_MASK; |
1512 |
> |
if ((p = w.parker) != null) |
1513 |
> |
U.unpark(p); // activate and release |
1514 |
> |
break; |
1515 |
> |
} |
1516 |
|
} |
1517 |
< |
} |
1323 |
< |
else if (e > 0 && ws != null && |
1324 |
< |
(i = ((~e << 1) | 1) & SMASK) < ws.length && |
1325 |
< |
(w = ws[i]) != null && |
1326 |
< |
w.eventCount == (e | INT_SIGN)) { |
1327 |
< |
if (U.compareAndSwapLong |
1328 |
< |
(this, CTL, c, (((long)(w.nextWait & E_MASK)) | |
1329 |
< |
((long)(u + UAC_UNIT) << 32)))) { |
1330 |
< |
w.eventCount = (e + E_SEQ) & E_MASK; |
1331 |
< |
if ((p = w.parker) != null) |
1332 |
< |
U.unpark(p); // release a waiting worker |
1517 |
> |
else |
1518 |
|
break; |
1334 |
– |
} |
1335 |
– |
} |
1336 |
– |
else |
1337 |
– |
break; |
1338 |
– |
} |
1339 |
– |
} |
1340 |
– |
|
1341 |
– |
/** |
1342 |
– |
* Tries to decrement active count (sometimes implicitly) and |
1343 |
– |
* possibly release or create a compensating worker in preparation |
1344 |
– |
* for blocking. Fails on contention or termination. |
1345 |
– |
* |
1346 |
– |
* @return true if the caller can block, else should recheck and retry |
1347 |
– |
*/ |
1348 |
– |
final boolean tryCompensate() { |
1349 |
– |
WorkQueue[] ws; WorkQueue w; Thread p; |
1350 |
– |
int pc = parallelism, e, u, ac, tc, i; |
1351 |
– |
long c = ctl; |
1352 |
– |
|
1353 |
– |
if ((e = (int)c) >= 0) { |
1354 |
– |
if ((ac = ((u = (int)(c >>> 32)) >> UAC_SHIFT)) <= 0 && |
1355 |
– |
e != 0 && (ws = workQueues) != null && |
1356 |
– |
(i = ((~e << 1) | 1) & SMASK) < ws.length && |
1357 |
– |
(w = ws[i]) != null) { |
1358 |
– |
if (w.eventCount == (e | INT_SIGN) && |
1359 |
– |
U.compareAndSwapLong |
1360 |
– |
(this, CTL, c, ((long)(w.nextWait & E_MASK) | |
1361 |
– |
(c & (AC_MASK|TC_MASK))))) { |
1362 |
– |
w.eventCount = (e + E_SEQ) & E_MASK; |
1363 |
– |
if ((p = w.parker) != null) |
1364 |
– |
U.unpark(p); |
1365 |
– |
return true; // release an idle worker |
1366 |
– |
} |
1367 |
– |
} |
1368 |
– |
else if ((tc = (short)(u >>> UTC_SHIFT)) >= 0 && ac + pc > 1) { |
1369 |
– |
long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK); |
1370 |
– |
if (U.compareAndSwapLong(this, CTL, c, nc)) |
1371 |
– |
return true; // no compensation needed |
1519 |
|
} |
1520 |
< |
else if (tc + pc < MAX_ID) { |
1521 |
< |
long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK); |
1520 |
> |
else if (e == 0 && (u & SHORT_SIGN) != 0) { // too few total |
1521 |
> |
long nc = (long)(((u + UTC_UNIT) & UTC_MASK) | |
1522 |
> |
((u + UAC_UNIT) & UAC_MASK)) << 32; |
1523 |
|
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
1524 |
|
addWorker(); |
1525 |
< |
return true; // create replacement |
1525 |
> |
break; |
1526 |
|
} |
1527 |
|
} |
1528 |
+ |
else |
1529 |
+ |
break; |
1530 |
|
} |
1381 |
– |
return false; |
1531 |
|
} |
1532 |
|
|
1533 |
< |
// Submissions |
1533 |
> |
// Scanning for tasks |
1534 |
|
|
1535 |
|
/** |
1536 |
< |
* Unless shutting down, adds the given task to a submission queue |
1388 |
< |
* at submitter's current queue index. If no queue exists at the |
1389 |
< |
* index, one is created unless pool lock is busy. If the queue |
1390 |
< |
* and/or lock are busy, another index is randomly chosen. |
1536 |
> |
* Top-level runloop for workers, called by ForkJoinWorkerThread.run. |
1537 |
|
*/ |
1538 |
< |
private void doSubmit(ForkJoinTask<?> task) { |
1539 |
< |
if (task == null) |
1540 |
< |
throw new NullPointerException(); |
1395 |
< |
Submitter s = submitters.get(); |
1396 |
< |
for (int r = s.seed;;) { |
1397 |
< |
WorkQueue q; int k; |
1398 |
< |
int rs = runState, m = rs & SMASK; |
1399 |
< |
WorkQueue[] ws = workQueues; |
1400 |
< |
if (rs < 0 || ws == null) // shutting down |
1401 |
< |
throw new RejectedExecutionException(); |
1402 |
< |
if (ws.length > m && // k must be at index |
1403 |
< |
((q = ws[k = (r << 1) & m]) != null || |
1404 |
< |
(q = tryAddSharedQueue(k)) != null) && |
1405 |
< |
q.trySharedPush(task)) { |
1406 |
< |
signalWork(); |
1407 |
< |
return; |
1408 |
< |
} |
1409 |
< |
r ^= r << 13; // xorshift seed to new position |
1410 |
< |
r ^= r >>> 17; |
1411 |
< |
if (((s.seed = r ^= r << 5) & m) == 0) |
1412 |
< |
Thread.yield(); // occasionally yield if busy |
1413 |
< |
} |
1538 |
> |
final void runWorker(WorkQueue w) { |
1539 |
> |
w.growArray(false); // initialize queue array in this thread |
1540 |
> |
do { w.runTask(scan(w)); } while (w.runState >= 0); |
1541 |
|
} |
1542 |
|
|
1416 |
– |
|
1417 |
– |
// Scanning for tasks |
1418 |
– |
|
1543 |
|
/** |
1544 |
|
* Scans for and, if found, returns one task, else possibly |
1545 |
|
* inactivates the worker. This method operates on single reads of |
1546 |
< |
* volatile state and is designed to be re-invoked continuously in |
1547 |
< |
* part because it returns upon detecting inconsistencies, |
1546 |
> |
* volatile state and is designed to be re-invoked continuously, |
1547 |
> |
* in part because it returns upon detecting inconsistencies, |
1548 |
|
* contention, or state changes that indicate possible success on |
1549 |
|
* re-invocation. |
1550 |
|
* |
1551 |
< |
* The scan searches for tasks across queues, randomly selecting |
1552 |
< |
* the first #queues probes, favoring steals 2:1 over submissions |
1553 |
< |
* (by exploiting even/odd indexing), and then performing a |
1554 |
< |
* circular sweep of all queues. The scan terminates upon either |
1555 |
< |
* finding a non-empty queue, or completing a full sweep. If the |
1556 |
< |
* worker is not inactivated, it takes and returns a task from |
1557 |
< |
* this queue. On failure to find a task, we take one of the |
1558 |
< |
* following actions, after which the caller will retry calling |
1559 |
< |
* this method unless terminated. |
1551 |
> |
* The scan searches for tasks across a random permutation of |
1552 |
> |
* queues (starting at a random index and stepping by a random |
1553 |
> |
* relative prime, checking each at least once). The scan |
1554 |
> |
* terminates upon either finding a non-empty queue, or completing |
1555 |
> |
* the sweep. If the worker is not inactivated, it takes and |
1556 |
> |
* returns a task from this queue. On failure to find a task, we |
1557 |
> |
* take one of the following actions, after which the caller will |
1558 |
> |
* retry calling this method unless terminated. |
1559 |
> |
* |
1560 |
> |
* * If pool is terminating, terminate the worker. |
1561 |
|
* |
1562 |
|
* * If not a complete sweep, try to release a waiting worker. If |
1563 |
|
* the scan terminated because the worker is inactivated, then the |
1566 |
|
* another worker, but with same net effect. Releasing in other |
1567 |
|
* cases as well ensures that we have enough workers running. |
1568 |
|
* |
1444 |
– |
* * If the caller has run a task since the the last empty scan, |
1445 |
– |
* return (to allow rescan) if other workers are not also yet |
1446 |
– |
* enqueued. Field WorkQueue.rescans counts down on each scan to |
1447 |
– |
* ensure eventual inactivation, and occasional calls to |
1448 |
– |
* Thread.yield to help avoid interference with more useful |
1449 |
– |
* activities on the system. |
1450 |
– |
* |
1451 |
– |
* * If pool is terminating, terminate the worker. |
1452 |
– |
* |
1569 |
|
* * If not already enqueued, try to inactivate and enqueue the |
1570 |
< |
* worker on wait queue. |
1570 |
> |
* worker on wait queue. Or, if inactivating has caused the pool |
1571 |
> |
* to be quiescent, relay to idleAwaitWork to check for |
1572 |
> |
* termination and possibly shrink pool. |
1573 |
> |
* |
1574 |
> |
* * If already inactive, and the caller has run a task since the |
1575 |
> |
* last empty scan, return (to allow rescan) unless others are |
1576 |
> |
* also inactivated. Field WorkQueue.rescans counts down on each |
1577 |
> |
* scan to ensure eventual inactivation and blocking. |
1578 |
|
* |
1579 |
< |
* * If already enqueued and none of the above apply, either park |
1580 |
< |
* awaiting signal, or if this is the most recent waiter and pool |
1458 |
< |
* is quiescent, relay to idleAwaitWork to check for termination |
1459 |
< |
* and possibly shrink pool. |
1579 |
> |
* * If already enqueued and none of the above apply, park |
1580 |
> |
* awaiting signal, |
1581 |
|
* |
1582 |
|
* @param w the worker (via its WorkQueue) |
1583 |
< |
* @return a task or null of none found |
1583 |
> |
* @return a task or null if none found |
1584 |
|
*/ |
1585 |
|
private final ForkJoinTask<?> scan(WorkQueue w) { |
1586 |
< |
boolean swept = false; // true after full empty scan |
1587 |
< |
WorkQueue[] ws; // volatile read order matters |
1588 |
< |
int r = w.seed, ec = w.eventCount; // ec is negative if inactive |
1589 |
< |
int rs = runState, m = rs & SMASK; |
1590 |
< |
if ((ws = workQueues) != null && ws.length > m) { |
1591 |
< |
ForkJoinTask<?> task = null; |
1592 |
< |
for (int k = 0, j = -2 - m; ; ++j) { |
1593 |
< |
WorkQueue q; int b; |
1594 |
< |
if (j < 0) { // random probes while j negative |
1595 |
< |
r ^= r << 13; r ^= r >>> 17; k = (r ^= r << 5) | (j & 1); |
1596 |
< |
} // worker (not submit) for odd j |
1597 |
< |
else // cyclic scan when j >= 0 |
1598 |
< |
k += (m >>> 1) | 1; // step by half to reduce bias |
1599 |
< |
|
1600 |
< |
if ((q = ws[k & m]) != null && (b = q.base) - q.top < 0) { |
1601 |
< |
if (ec >= 0) |
1602 |
< |
task = q.pollAt(b); // steal |
1603 |
< |
break; |
1586 |
> |
WorkQueue[] ws; // first update random seed |
1587 |
> |
int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5; |
1588 |
> |
int rs = runState, m; // volatile read order matters |
1589 |
> |
if ((ws = workQueues) != null && (m = ws.length - 1) > 0) { |
1590 |
> |
int ec = w.eventCount; // ec is negative if inactive |
1591 |
> |
int step = (r >>> 16) | 1; // relative prime |
1592 |
> |
for (int j = (m + 1) << 2; ; r += step) { |
1593 |
> |
WorkQueue q; ForkJoinTask<?> t; ForkJoinTask<?>[] a; int b; |
1594 |
> |
if ((q = ws[r & m]) != null && (b = q.base) - q.top < 0 && |
1595 |
> |
(a = q.array) != null) { // probably nonempty |
1596 |
> |
int i = (((a.length - 1) & b) << ASHIFT) + ABASE; |
1597 |
> |
t = (ForkJoinTask<?>)U.getObjectVolatile(a, i); |
1598 |
> |
if (q.base == b && ec >= 0 && t != null && |
1599 |
> |
U.compareAndSwapObject(a, i, t, null)) { |
1600 |
> |
if (q.top - (q.base = b + 1) > 0) |
1601 |
> |
signalWork(); // help pushes signal |
1602 |
> |
return t; |
1603 |
> |
} |
1604 |
> |
else if (ec < 0 || j <= m) { |
1605 |
> |
rs = 0; // mark scan as imcomplete |
1606 |
> |
break; // caller can retry after release |
1607 |
> |
} |
1608 |
|
} |
1609 |
< |
else if (j > m) { |
1485 |
< |
if (rs == runState) // staleness check |
1486 |
< |
swept = true; |
1609 |
> |
if (--j < 0) |
1610 |
|
break; |
1611 |
+ |
} |
1612 |
+ |
|
1613 |
+ |
long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns; |
1614 |
+ |
if (e < 0) // decode ctl on empty scan |
1615 |
+ |
w.runState = -1; // pool is terminating |
1616 |
+ |
else if (rs == 0 || rs != runState) { // incomplete scan |
1617 |
+ |
WorkQueue v; Thread p; // try to release a waiter |
1618 |
+ |
if (e > 0 && a < 0 && w.eventCount == ec && |
1619 |
+ |
(v = ws[e & m]) != null && v.eventCount == (e | INT_SIGN)) { |
1620 |
+ |
long nc = ((long)(v.nextWait & E_MASK) | |
1621 |
+ |
((c + AC_UNIT) & (AC_MASK|TC_MASK))); |
1622 |
+ |
if (ctl == c && U.compareAndSwapLong(this, CTL, c, nc)) { |
1623 |
+ |
v.eventCount = (e + E_SEQ) & E_MASK; |
1624 |
+ |
if ((p = v.parker) != null) |
1625 |
+ |
U.unpark(p); |
1626 |
+ |
} |
1627 |
|
} |
1628 |
|
} |
1629 |
< |
w.seed = r; // save seed for next scan |
1630 |
< |
if (task != null) |
1631 |
< |
return task; |
1632 |
< |
} |
1633 |
< |
|
1634 |
< |
// Decode ctl on empty scan |
1635 |
< |
long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns; |
1636 |
< |
if (!swept) { // try to release a waiter |
1637 |
< |
WorkQueue v; Thread p; |
1638 |
< |
if (e > 0 && a < 0 && ws != null && |
1639 |
< |
(v = ws[((~e << 1) | 1) & m]) != null && |
1640 |
< |
v.eventCount == (e | INT_SIGN) && U.compareAndSwapLong |
1641 |
< |
(this, CTL, c, ((long)(v.nextWait & E_MASK) | |
1642 |
< |
((c + AC_UNIT) & (AC_MASK|TC_MASK))))) { |
1643 |
< |
v.eventCount = (e + E_SEQ) & E_MASK; |
1644 |
< |
if ((p = v.parker) != null) |
1645 |
< |
U.unpark(p); |
1646 |
< |
} |
1647 |
< |
} |
1648 |
< |
else if ((nr = w.rescans) > 0) { // continue rescanning |
1649 |
< |
int ac = a + parallelism; |
1650 |
< |
if ((w.rescans = (ac < nr) ? ac : nr - 1) > 0 && w.seed < 0 && |
1651 |
< |
w.eventCount == ec) |
1652 |
< |
Thread.yield(); // 1 bit randomness for yield call |
1653 |
< |
} |
1654 |
< |
else if (e < 0) // pool is terminating |
1655 |
< |
w.runState = -1; |
1656 |
< |
else if (ec >= 0) { // try to enqueue |
1657 |
< |
long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK)); |
1658 |
< |
w.nextWait = e; |
1520 |
< |
w.eventCount = ec | INT_SIGN; // mark as inactive |
1521 |
< |
if (!U.compareAndSwapLong(this, CTL, c, nc)) |
1522 |
< |
w.eventCount = ec; // back out on CAS failure |
1523 |
< |
else if ((ns = w.nsteals) != 0) { // set rescans if ran task |
1524 |
< |
if (a <= 0) // ... unless too many active |
1525 |
< |
w.rescans = a + parallelism; |
1526 |
< |
w.nsteals = 0; |
1527 |
< |
w.totalSteals += ns; |
1528 |
< |
} |
1529 |
< |
} |
1530 |
< |
else{ // already queued |
1531 |
< |
if (parallelism == -a) |
1532 |
< |
idleAwaitWork(w); // quiescent |
1533 |
< |
if (w.eventCount == ec) { |
1534 |
< |
Thread.interrupted(); // clear status |
1535 |
< |
ForkJoinWorkerThread wt = w.owner; |
1536 |
< |
U.putObject(wt, PARKBLOCKER, this); |
1537 |
< |
w.parker = wt; // emulate LockSupport.park |
1538 |
< |
if (w.eventCount == ec) // recheck |
1539 |
< |
U.park(false, 0L); // block |
1540 |
< |
w.parker = null; |
1541 |
< |
U.putObject(wt, PARKBLOCKER, null); |
1629 |
> |
else if (ec >= 0) { // try to enqueue/inactivate |
1630 |
> |
long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK)); |
1631 |
> |
w.nextWait = e; |
1632 |
> |
w.eventCount = ec | INT_SIGN; // mark as inactive |
1633 |
> |
if (ctl != c || !U.compareAndSwapLong(this, CTL, c, nc)) |
1634 |
> |
w.eventCount = ec; // unmark on CAS failure |
1635 |
> |
else { |
1636 |
> |
if ((ns = w.nsteals) != 0) { |
1637 |
> |
w.nsteals = 0; // set rescans if ran task |
1638 |
> |
w.rescans = (a > 0) ? 0 : a + parallelism; |
1639 |
> |
w.totalSteals += ns; |
1640 |
> |
} |
1641 |
> |
if (a == 1 - parallelism) // quiescent |
1642 |
> |
idleAwaitWork(w, nc, c); |
1643 |
> |
} |
1644 |
> |
} |
1645 |
> |
else if (w.eventCount < 0) { // already queued |
1646 |
> |
int ac = a + parallelism; |
1647 |
> |
if ((nr = w.rescans) > 0) // continue rescanning |
1648 |
> |
w.rescans = (ac < nr) ? ac : nr - 1; |
1649 |
> |
else if (((w.seed >>> 16) & ac) == 0) { // randomize park |
1650 |
> |
Thread.interrupted(); // clear status |
1651 |
> |
Thread wt = Thread.currentThread(); |
1652 |
> |
U.putObject(wt, PARKBLOCKER, this); |
1653 |
> |
w.parker = wt; // emulate LockSupport.park |
1654 |
> |
if (w.eventCount < 0) // recheck |
1655 |
> |
U.park(false, 0L); |
1656 |
> |
w.parker = null; |
1657 |
> |
U.putObject(wt, PARKBLOCKER, null); |
1658 |
> |
} |
1659 |
|
} |
1660 |
|
} |
1661 |
|
return null; |
1662 |
|
} |
1663 |
|
|
1664 |
|
/** |
1665 |
< |
* If inactivating worker w has caused pool to become quiescent, |
1666 |
< |
* checks for pool termination, and, so long as this is not the |
1667 |
< |
* only worker, waits for event for up to SHRINK_RATE nanosecs. |
1668 |
< |
* On timeout, if ctl has not changed, terminates the worker, |
1669 |
< |
* which will in turn wake up another worker to possibly repeat |
1670 |
< |
* this process. |
1665 |
> |
* If inactivating worker w has caused the pool to become |
1666 |
> |
* quiescent, checks for pool termination, and, so long as this is |
1667 |
> |
* not the only worker, waits for event for up to a given |
1668 |
> |
* duration. On timeout, if ctl has not changed, terminates the |
1669 |
> |
* worker, which will in turn wake up another worker to possibly |
1670 |
> |
* repeat this process. |
1671 |
|
* |
1672 |
|
* @param w the calling worker |
1673 |
+ |
* @param currentCtl the ctl value triggering possible quiescence |
1674 |
+ |
* @param prevCtl the ctl value to restore if thread is terminated |
1675 |
|
*/ |
1676 |
< |
private void idleAwaitWork(WorkQueue w) { |
1677 |
< |
long c; int nw, ec; |
1678 |
< |
if (!tryTerminate(false) && |
1679 |
< |
(int)((c = ctl) >> AC_SHIFT) + parallelism == 0 && |
1680 |
< |
(ec = w.eventCount) == ((int)c | INT_SIGN) && |
1681 |
< |
(nw = w.nextWait) != 0) { |
1682 |
< |
long nc = ((long)(nw & E_MASK) | // ctl to restore on timeout |
1683 |
< |
((c + AC_UNIT) & AC_MASK) | (c & TC_MASK)); |
1565 |
< |
ForkJoinTask.helpExpungeStaleExceptions(); // help clean |
1566 |
< |
ForkJoinWorkerThread wt = w.owner; |
1567 |
< |
while (ctl == c) { |
1568 |
< |
long startTime = System.nanoTime(); |
1676 |
> |
private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) { |
1677 |
> |
if (w.eventCount < 0 && !tryTerminate(false, false) && |
1678 |
> |
(int)prevCtl != 0 && !hasQueuedSubmissions() && ctl == currentCtl) { |
1679 |
> |
int dc = -(short)(currentCtl >>> TC_SHIFT); |
1680 |
> |
long parkTime = dc < 0 ? FAST_IDLE_TIMEOUT: (dc + 1) * IDLE_TIMEOUT; |
1681 |
> |
long deadline = System.nanoTime() + parkTime - 100000L; // 1ms slop |
1682 |
> |
Thread wt = Thread.currentThread(); |
1683 |
> |
while (ctl == currentCtl) { |
1684 |
|
Thread.interrupted(); // timed variant of version in scan() |
1685 |
|
U.putObject(wt, PARKBLOCKER, this); |
1686 |
|
w.parker = wt; |
1687 |
< |
if (ctl == c) |
1688 |
< |
U.park(false, SHRINK_RATE); |
1687 |
> |
if (ctl == currentCtl) |
1688 |
> |
U.park(false, parkTime); |
1689 |
|
w.parker = null; |
1690 |
|
U.putObject(wt, PARKBLOCKER, null); |
1691 |
< |
if (ctl != c) |
1691 |
> |
if (ctl != currentCtl) |
1692 |
|
break; |
1693 |
< |
if (System.nanoTime() - startTime >= SHRINK_TIMEOUT && |
1694 |
< |
U.compareAndSwapLong(this, CTL, c, nc)) { |
1695 |
< |
w.runState = -1; // shrink |
1696 |
< |
w.eventCount = (ec + E_SEQ) | E_MASK; |
1693 |
> |
if (deadline - System.nanoTime() <= 0L && |
1694 |
> |
U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) { |
1695 |
> |
w.eventCount = (w.eventCount + E_SEQ) | E_MASK; |
1696 |
> |
w.runState = -1; // shrink |
1697 |
|
break; |
1698 |
|
} |
1699 |
|
} |
1711 |
|
* leaves hints in workers to speed up subsequent calls. The |
1712 |
|
* implementation is very branchy to cope with potential |
1713 |
|
* inconsistencies or loops encountering chains that are stale, |
1714 |
< |
* unknown, or of length greater than MAX_HELP_DEPTH links. All |
1600 |
< |
* of these cases are dealt with by just retrying by caller. |
1714 |
> |
* unknown, or so long that they are likely cyclic. |
1715 |
|
* |
1716 |
|
* @param joiner the joining worker |
1717 |
|
* @param task the task to join |
1718 |
< |
* @return true if found or ran a task (and so is immediately retryable) |
1718 |
> |
* @return 0 if no progress can be made, negative if task |
1719 |
> |
* known complete, else positive |
1720 |
|
*/ |
1721 |
< |
final boolean tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) { |
1722 |
< |
ForkJoinTask<?> subtask; // current target |
1723 |
< |
boolean progress = false; |
1724 |
< |
int depth = 0; // current chain depth |
1725 |
< |
int m = runState & SMASK; |
1726 |
< |
WorkQueue[] ws = workQueues; |
1727 |
< |
|
1728 |
< |
if (ws != null && ws.length > m && (subtask = task).status >= 0) { |
1729 |
< |
outer:for (WorkQueue j = joiner;;) { |
1730 |
< |
// Try to find the stealer of subtask, by first using hint |
1616 |
< |
WorkQueue stealer = null; |
1617 |
< |
WorkQueue v = ws[j.stealHint & m]; |
1618 |
< |
if (v != null && v.currentSteal == subtask) |
1619 |
< |
stealer = v; |
1620 |
< |
else { |
1621 |
< |
for (int i = 1; i <= m; i += 2) { |
1622 |
< |
if ((v = ws[i]) != null && v.currentSteal == subtask) { |
1623 |
< |
stealer = v; |
1624 |
< |
j.stealHint = i; // save hint |
1625 |
< |
break; |
1626 |
< |
} |
1721 |
> |
private int tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) { |
1722 |
> |
int stat = 0, steps = 0; // bound to avoid cycles |
1723 |
> |
if (joiner != null && task != null) { // hoist null checks |
1724 |
> |
restart: for (;;) { |
1725 |
> |
ForkJoinTask<?> subtask = task; // current target |
1726 |
> |
for (WorkQueue j = joiner, v;;) { // v is stealer of subtask |
1727 |
> |
WorkQueue[] ws; int m, s, h; |
1728 |
> |
if ((s = task.status) < 0) { |
1729 |
> |
stat = s; |
1730 |
> |
break restart; |
1731 |
|
} |
1732 |
< |
if (stealer == null) |
1733 |
< |
break; |
1734 |
< |
} |
1735 |
< |
|
1736 |
< |
for (WorkQueue q = stealer;;) { // Try to help stealer |
1737 |
< |
ForkJoinTask<?> t; int b; |
1738 |
< |
if (task.status < 0) |
1739 |
< |
break outer; |
1740 |
< |
if ((b = q.base) - q.top < 0) { |
1741 |
< |
progress = true; |
1742 |
< |
if (subtask.status < 0) |
1743 |
< |
break outer; // stale |
1744 |
< |
if ((t = q.pollAt(b)) != null) { |
1745 |
< |
stealer.stealHint = joiner.poolIndex; |
1746 |
< |
joiner.runSubtask(t); |
1732 |
> |
if ((ws = workQueues) == null || (m = ws.length - 1) <= 0) |
1733 |
> |
break restart; // shutting down |
1734 |
> |
if ((v = ws[h = (j.stealHint | 1) & m]) == null || |
1735 |
> |
v.currentSteal != subtask) { |
1736 |
> |
for (int origin = h;;) { // find stealer |
1737 |
> |
if (((h = (h + 2) & m) & 15) == 1 && |
1738 |
> |
(subtask.status < 0 || j.currentJoin != subtask)) |
1739 |
> |
continue restart; // occasional staleness check |
1740 |
> |
if ((v = ws[h]) != null && |
1741 |
> |
v.currentSteal == subtask) { |
1742 |
> |
j.stealHint = h; // save hint |
1743 |
> |
break; |
1744 |
> |
} |
1745 |
> |
if (h == origin) |
1746 |
> |
break restart; // cannot find stealer |
1747 |
|
} |
1748 |
|
} |
1749 |
< |
else { // empty - try to descend to find stealer's stealer |
1750 |
< |
ForkJoinTask<?> next = stealer.currentJoin; |
1751 |
< |
if (++depth == MAX_HELP_DEPTH || subtask.status < 0 || |
1752 |
< |
next == null || next == subtask) |
1753 |
< |
break outer; // max depth, stale, dead-end, cyclic |
1754 |
< |
subtask = next; |
1755 |
< |
j = stealer; |
1756 |
< |
break; |
1749 |
> |
for (;;) { // help stealer or descend to its stealer |
1750 |
> |
ForkJoinTask[] a; int b; |
1751 |
> |
if (subtask.status < 0) // surround probes with |
1752 |
> |
continue restart; // consistency checks |
1753 |
> |
if ((b = v.base) - v.top < 0 && (a = v.array) != null) { |
1754 |
> |
int i = (((a.length - 1) & b) << ASHIFT) + ABASE; |
1755 |
> |
ForkJoinTask<?> t = |
1756 |
> |
(ForkJoinTask<?>)U.getObjectVolatile(a, i); |
1757 |
> |
if (subtask.status < 0 || j.currentJoin != subtask || |
1758 |
> |
v.currentSteal != subtask) |
1759 |
> |
continue restart; // stale |
1760 |
> |
stat = 1; // apparent progress |
1761 |
> |
if (t != null && v.base == b && |
1762 |
> |
U.compareAndSwapObject(a, i, t, null)) { |
1763 |
> |
v.base = b + 1; // help stealer |
1764 |
> |
joiner.runSubtask(t); |
1765 |
> |
} |
1766 |
> |
else if (v.base == b && ++steps == MAX_HELP) |
1767 |
> |
break restart; // v apparently stalled |
1768 |
> |
} |
1769 |
> |
else { // empty -- try to descend |
1770 |
> |
ForkJoinTask<?> next = v.currentJoin; |
1771 |
> |
if (subtask.status < 0 || j.currentJoin != subtask || |
1772 |
> |
v.currentSteal != subtask) |
1773 |
> |
continue restart; // stale |
1774 |
> |
else if (next == null || ++steps == MAX_HELP) |
1775 |
> |
break restart; // dead-end or maybe cyclic |
1776 |
> |
else { |
1777 |
> |
subtask = next; |
1778 |
> |
j = v; |
1779 |
> |
break; |
1780 |
> |
} |
1781 |
> |
} |
1782 |
|
} |
1783 |
|
} |
1784 |
|
} |
1785 |
|
} |
1786 |
< |
return progress; |
1786 |
> |
return stat; |
1787 |
|
} |
1788 |
|
|
1789 |
|
/** |
1792 |
|
* @param joiner the joining worker |
1793 |
|
* @param task the task |
1794 |
|
*/ |
1795 |
< |
final void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) { |
1795 |
> |
private void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) { |
1796 |
|
WorkQueue[] ws; |
1797 |
< |
int m = runState & SMASK; |
1798 |
< |
if ((ws = workQueues) != null && ws.length > m) { |
1670 |
< |
for (int j = 1; j <= m && task.status >= 0; j += 2) { |
1797 |
> |
if ((ws = workQueues) != null) { |
1798 |
> |
for (int j = 1; j < ws.length && task.status >= 0; j += 2) { |
1799 |
|
WorkQueue q = ws[j]; |
1800 |
|
if (q != null && q.pollFor(task)) { |
1801 |
|
joiner.runSubtask(task); |
1806 |
|
} |
1807 |
|
|
1808 |
|
/** |
1809 |
< |
* Returns a non-empty steal queue, if one is found during a random, |
1810 |
< |
* then cyclic scan, else null. This method must be retried by |
1811 |
< |
* caller if, by the time it tries to use the queue, it is empty. |
1809 |
> |
* Tries to decrement active count (sometimes implicitly) and |
1810 |
> |
* possibly release or create a compensating worker in preparation |
1811 |
> |
* for blocking. Fails on contention or termination. Otherwise, |
1812 |
> |
* adds a new thread if no idle workers are available and either |
1813 |
> |
* pool would become completely starved or: (at least half |
1814 |
> |
* starved, and fewer than 50% spares exist, and there is at least |
1815 |
> |
* one task apparently available). Even though the availability |
1816 |
> |
* check requires a full scan, it is worthwhile in reducing false |
1817 |
> |
* alarms. |
1818 |
> |
* |
1819 |
> |
* @param task if non-null, a task being waited for |
1820 |
> |
* @param blocker if non-null, a blocker being waited for |
1821 |
> |
* @return true if the caller can block, else should recheck and retry |
1822 |
> |
*/ |
1823 |
> |
final boolean tryCompensate(ForkJoinTask<?> task, ManagedBlocker blocker) { |
1824 |
> |
int pc = parallelism, e; |
1825 |
> |
long c = ctl; |
1826 |
> |
WorkQueue[] ws = workQueues; |
1827 |
> |
if ((e = (int)c) >= 0 && ws != null) { |
1828 |
> |
int u, a, ac, hc; |
1829 |
> |
int tc = (short)((u = (int)(c >>> 32)) >>> UTC_SHIFT) + pc; |
1830 |
> |
boolean replace = false; |
1831 |
> |
if ((a = u >> UAC_SHIFT) <= 0) { |
1832 |
> |
if ((ac = a + pc) <= 1) |
1833 |
> |
replace = true; |
1834 |
> |
else if ((e > 0 || (task != null && |
1835 |
> |
ac <= (hc = pc >>> 1) && tc < pc + hc))) { |
1836 |
> |
WorkQueue w; |
1837 |
> |
for (int j = 0; j < ws.length; ++j) { |
1838 |
> |
if ((w = ws[j]) != null && !w.isEmpty()) { |
1839 |
> |
replace = true; |
1840 |
> |
break; // in compensation range and tasks available |
1841 |
> |
} |
1842 |
> |
} |
1843 |
> |
} |
1844 |
> |
} |
1845 |
> |
if ((task == null || task.status >= 0) && // recheck need to block |
1846 |
> |
(blocker == null || !blocker.isReleasable()) && ctl == c) { |
1847 |
> |
if (!replace) { // no compensation |
1848 |
> |
long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK); |
1849 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) |
1850 |
> |
return true; |
1851 |
> |
} |
1852 |
> |
else if (e != 0) { // release an idle worker |
1853 |
> |
WorkQueue w; Thread p; int i; |
1854 |
> |
if ((i = e & SMASK) < ws.length && (w = ws[i]) != null) { |
1855 |
> |
long nc = ((long)(w.nextWait & E_MASK) | |
1856 |
> |
(c & (AC_MASK|TC_MASK))); |
1857 |
> |
if (w.eventCount == (e | INT_SIGN) && |
1858 |
> |
U.compareAndSwapLong(this, CTL, c, nc)) { |
1859 |
> |
w.eventCount = (e + E_SEQ) & E_MASK; |
1860 |
> |
if ((p = w.parker) != null) |
1861 |
> |
U.unpark(p); |
1862 |
> |
return true; |
1863 |
> |
} |
1864 |
> |
} |
1865 |
> |
} |
1866 |
> |
else if (tc < MAX_CAP) { // create replacement |
1867 |
> |
long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK); |
1868 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
1869 |
> |
addWorker(); |
1870 |
> |
return true; |
1871 |
> |
} |
1872 |
> |
} |
1873 |
> |
} |
1874 |
> |
} |
1875 |
> |
return false; |
1876 |
> |
} |
1877 |
> |
|
1878 |
> |
/** |
1879 |
> |
* Helps and/or blocks until the given task is done. |
1880 |
> |
* |
1881 |
> |
* @param joiner the joining worker |
1882 |
> |
* @param task the task |
1883 |
> |
* @return task status on exit |
1884 |
> |
*/ |
1885 |
> |
final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) { |
1886 |
> |
int s; |
1887 |
> |
if ((s = task.status) >= 0) { |
1888 |
> |
ForkJoinTask<?> prevJoin = joiner.currentJoin; |
1889 |
> |
joiner.currentJoin = task; |
1890 |
> |
long startTime = 0L; |
1891 |
> |
for (int k = 0;;) { |
1892 |
> |
if ((s = (joiner.isEmpty() ? // try to help |
1893 |
> |
tryHelpStealer(joiner, task) : |
1894 |
> |
joiner.tryRemoveAndExec(task))) == 0 && |
1895 |
> |
(s = task.status) >= 0) { |
1896 |
> |
if (k == 0) { |
1897 |
> |
startTime = System.nanoTime(); |
1898 |
> |
tryPollForAndExec(joiner, task); // check uncommon case |
1899 |
> |
} |
1900 |
> |
else if ((k & (MAX_HELP - 1)) == 0 && |
1901 |
> |
System.nanoTime() - startTime >= |
1902 |
> |
COMPENSATION_DELAY && |
1903 |
> |
tryCompensate(task, null)) { |
1904 |
> |
if (task.trySetSignal()) { |
1905 |
> |
synchronized (task) { |
1906 |
> |
if (task.status >= 0) { |
1907 |
> |
try { // see ForkJoinTask |
1908 |
> |
task.wait(); // for explanation |
1909 |
> |
} catch (InterruptedException ie) { |
1910 |
> |
} |
1911 |
> |
} |
1912 |
> |
else |
1913 |
> |
task.notifyAll(); |
1914 |
> |
} |
1915 |
> |
} |
1916 |
> |
long c; // re-activate |
1917 |
> |
do {} while (!U.compareAndSwapLong |
1918 |
> |
(this, CTL, c = ctl, c + AC_UNIT)); |
1919 |
> |
} |
1920 |
> |
} |
1921 |
> |
if (s < 0 || (s = task.status) < 0) { |
1922 |
> |
joiner.currentJoin = prevJoin; |
1923 |
> |
break; |
1924 |
> |
} |
1925 |
> |
else if ((k++ & (MAX_HELP - 1)) == MAX_HELP >>> 1) |
1926 |
> |
Thread.yield(); // for politeness |
1927 |
> |
} |
1928 |
> |
} |
1929 |
> |
return s; |
1930 |
> |
} |
1931 |
> |
|
1932 |
> |
/** |
1933 |
> |
* Stripped-down variant of awaitJoin used by timed joins. Tries |
1934 |
> |
* to help join only while there is continuous progress. (Caller |
1935 |
> |
* will then enter a timed wait.) |
1936 |
> |
* |
1937 |
> |
* @param joiner the joining worker |
1938 |
> |
* @param task the task |
1939 |
> |
* @return task status on exit |
1940 |
> |
*/ |
1941 |
> |
final int helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) { |
1942 |
> |
int s; |
1943 |
> |
while ((s = task.status) >= 0 && |
1944 |
> |
(joiner.isEmpty() ? |
1945 |
> |
tryHelpStealer(joiner, task) : |
1946 |
> |
joiner.tryRemoveAndExec(task)) != 0) |
1947 |
> |
; |
1948 |
> |
return s; |
1949 |
> |
} |
1950 |
> |
|
1951 |
> |
/** |
1952 |
> |
* Returns a (probably) non-empty steal queue, if one is found |
1953 |
> |
* during a random, then cyclic scan, else null. This method must |
1954 |
> |
* be retried by caller if, by the time it tries to use the queue, |
1955 |
> |
* it is empty. |
1956 |
|
*/ |
1957 |
|
private WorkQueue findNonEmptyStealQueue(WorkQueue w) { |
1958 |
< |
int r = w.seed; // Same idea as scan(), but ignoring submissions |
1958 |
> |
// Similar to loop in scan(), but ignoring submissions |
1959 |
> |
int r; |
1960 |
> |
if (w == null) // allow external callers |
1961 |
> |
r = ThreadLocalRandom.current().nextInt(); |
1962 |
> |
else { |
1963 |
> |
r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5; |
1964 |
> |
} |
1965 |
> |
int step = (r >>> 16) | 1; |
1966 |
|
for (WorkQueue[] ws;;) { |
1967 |
< |
int m = runState & SMASK; |
1968 |
< |
if ((ws = workQueues) == null) |
1967 |
> |
int rs = runState, m; |
1968 |
> |
if ((ws = workQueues) == null || (m = ws.length - 1) < 1) |
1969 |
|
return null; |
1970 |
< |
if (ws.length > m) { |
1971 |
< |
WorkQueue q; |
1972 |
< |
for (int n = m << 2, k = r, j = -n;;) { |
1973 |
< |
r ^= r << 13; r ^= r >>> 17; r ^= r << 5; |
1974 |
< |
if ((q = ws[(k | 1) & m]) != null && q.base - q.top < 0) { |
1975 |
< |
w.seed = r; |
1697 |
< |
return q; |
1698 |
< |
} |
1699 |
< |
else if (j > n) |
1970 |
> |
for (int j = (m + 1) << 2; ; r += step) { |
1971 |
> |
WorkQueue q = ws[((r << 1) | 1) & m]; |
1972 |
> |
if (q != null && !q.isEmpty()) |
1973 |
> |
return q; |
1974 |
> |
else if (--j < 0) { |
1975 |
> |
if (runState == rs) |
1976 |
|
return null; |
1977 |
< |
else |
1702 |
< |
k = (j++ < 0) ? r : k + ((m >>> 1) | 1); |
1703 |
< |
|
1977 |
> |
break; |
1978 |
|
} |
1979 |
|
} |
1980 |
|
} |
1988 |
|
*/ |
1989 |
|
final void helpQuiescePool(WorkQueue w) { |
1990 |
|
for (boolean active = true;;) { |
1991 |
< |
w.runLocalTasks(); // exhaust local queue |
1991 |
> |
ForkJoinTask<?> localTask; // exhaust local queue |
1992 |
> |
while ((localTask = w.nextLocalTask()) != null) |
1993 |
> |
localTask.doExec(); |
1994 |
|
WorkQueue q = findNonEmptyStealQueue(w); |
1995 |
|
if (q != null) { |
1996 |
< |
ForkJoinTask<?> t; |
1996 |
> |
ForkJoinTask<?> t; int b; |
1997 |
|
if (!active) { // re-establish active count |
1998 |
|
long c; |
1999 |
|
active = true; |
2000 |
|
do {} while (!U.compareAndSwapLong |
2001 |
|
(this, CTL, c = ctl, c + AC_UNIT)); |
2002 |
|
} |
2003 |
< |
if ((t = q.poll()) != null) |
2003 |
> |
if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null) |
2004 |
|
w.runSubtask(t); |
2005 |
|
} |
2006 |
|
else { |
2022 |
|
} |
2023 |
|
|
2024 |
|
/** |
2025 |
+ |
* Restricted version of helpQuiescePool for non-FJ callers |
2026 |
+ |
*/ |
2027 |
+ |
static void externalHelpQuiescePool() { |
2028 |
+ |
ForkJoinPool p; WorkQueue[] ws; WorkQueue w, q; |
2029 |
+ |
ForkJoinTask<?> t; int b; |
2030 |
+ |
int k = submitters.get().seed & SQMASK; |
2031 |
+ |
if ((p = commonPool) != null && |
2032 |
+ |
(ws = p.workQueues) != null && |
2033 |
+ |
ws.length > (k &= p.submitMask) && |
2034 |
+ |
(w = ws[k]) != null && |
2035 |
+ |
(q = p.findNonEmptyStealQueue(w)) != null && |
2036 |
+ |
(b = q.base) - q.top < 0 && |
2037 |
+ |
(t = q.pollAt(b)) != null) |
2038 |
+ |
t.doExec(); |
2039 |
+ |
} |
2040 |
+ |
|
2041 |
+ |
/** |
2042 |
|
* Gets and removes a local or stolen task for the given worker. |
2043 |
|
* |
2044 |
|
* @return a task, if available |
2045 |
|
*/ |
2046 |
|
final ForkJoinTask<?> nextTaskFor(WorkQueue w) { |
2047 |
|
for (ForkJoinTask<?> t;;) { |
2048 |
< |
WorkQueue q; |
2048 |
> |
WorkQueue q; int b; |
2049 |
|
if ((t = w.nextLocalTask()) != null) |
2050 |
|
return t; |
2051 |
|
if ((q = findNonEmptyStealQueue(w)) == null) |
2052 |
|
return null; |
2053 |
< |
if ((t = q.poll()) != null) |
2053 |
> |
if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null) |
2054 |
|
return t; |
2055 |
|
} |
2056 |
|
} |
2071 |
|
8); |
2072 |
|
} |
2073 |
|
|
1781 |
– |
// Termination |
1782 |
– |
|
2074 |
|
/** |
2075 |
< |
* Sets SHUTDOWN bit of runState under lock |
2075 |
> |
* Returns approximate submission queue length for the given caller |
2076 |
|
*/ |
2077 |
< |
private void enableShutdown() { |
2078 |
< |
ReentrantLock lock = this.lock; |
2079 |
< |
if (runState >= 0) { |
2080 |
< |
lock.lock(); // don't need try/finally |
2081 |
< |
runState |= SHUTDOWN; |
2082 |
< |
lock.unlock(); |
2083 |
< |
} |
2077 |
> |
static int getEstimatedSubmitterQueueLength() { |
2078 |
> |
ForkJoinPool p; WorkQueue[] ws; WorkQueue q; |
2079 |
> |
int k = submitters.get().seed & SQMASK; |
2080 |
> |
return ((p = commonPool) != null && |
2081 |
> |
p.runState >= 0 && |
2082 |
> |
(ws = p.workQueues) != null && |
2083 |
> |
ws.length > (k &= p.submitMask) && |
2084 |
> |
(q = ws[k]) != null) ? |
2085 |
> |
q.queueSize() : 0; |
2086 |
|
} |
2087 |
|
|
2088 |
+ |
// Termination |
2089 |
+ |
|
2090 |
|
/** |
2091 |
< |
* Possibly initiates and/or completes termination. Upon |
2092 |
< |
* termination, cancels all queued tasks and then |
2091 |
> |
* Possibly initiates and/or completes termination. The caller |
2092 |
> |
* triggering termination runs three passes through workQueues: |
2093 |
> |
* (0) Setting termination status, followed by wakeups of queued |
2094 |
> |
* workers; (1) cancelling all tasks; (2) interrupting lagging |
2095 |
> |
* threads (likely in external tasks, but possibly also blocked in |
2096 |
> |
* joins). Each pass repeats previous steps because of potential |
2097 |
> |
* lagging thread creation. |
2098 |
|
* |
2099 |
|
* @param now if true, unconditionally terminate, else only |
2100 |
|
* if no work and no active workers |
2101 |
+ |
* @param enable if true, enable shutdown when next possible |
2102 |
|
* @return true if now terminating or terminated |
2103 |
|
*/ |
2104 |
< |
private boolean tryTerminate(boolean now) { |
2104 |
> |
private boolean tryTerminate(boolean now, boolean enable) { |
2105 |
> |
Mutex lock = this.lock; |
2106 |
|
for (long c;;) { |
2107 |
|
if (((c = ctl) & STOP_BIT) != 0) { // already terminating |
2108 |
|
if ((short)(c >>> TC_SHIFT) == -parallelism) { |
1807 |
– |
ReentrantLock lock = this.lock; // signal when no workers |
2109 |
|
lock.lock(); // don't need try/finally |
2110 |
|
termination.signalAll(); // signal when 0 workers |
2111 |
|
lock.unlock(); |
2112 |
|
} |
2113 |
|
return true; |
2114 |
|
} |
2115 |
< |
if (!now) { |
2116 |
< |
if ((int)(c >> AC_SHIFT) != -parallelism || runState >= 0 || |
2115 |
> |
if (runState >= 0) { // not yet enabled |
2116 |
> |
if (!enable) |
2117 |
> |
return false; |
2118 |
> |
lock.lock(); |
2119 |
> |
runState |= SHUTDOWN; |
2120 |
> |
lock.unlock(); |
2121 |
> |
} |
2122 |
> |
if (!now) { // check if idle & no tasks |
2123 |
> |
if ((int)(c >> AC_SHIFT) != -parallelism || |
2124 |
|
hasQueuedSubmissions()) |
2125 |
|
return false; |
2126 |
|
// Check for unqueued inactive workers. One pass suffices. |
2127 |
|
WorkQueue[] ws = workQueues; WorkQueue w; |
2128 |
|
if (ws != null) { |
2129 |
< |
int n = ws.length; |
1822 |
< |
for (int i = 1; i < n; i += 2) { |
2129 |
> |
for (int i = 1; i < ws.length; i += 2) { |
2130 |
|
if ((w = ws[i]) != null && w.eventCount >= 0) |
2131 |
|
return false; |
2132 |
|
} |
2133 |
|
} |
2134 |
|
} |
2135 |
< |
if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) |
2136 |
< |
startTerminating(); |
2137 |
< |
} |
2138 |
< |
} |
2139 |
< |
|
2140 |
< |
/** |
2141 |
< |
* Initiates termination: Runs three passes through workQueues: |
2142 |
< |
* (0) Setting termination status, followed by wakeups of queued |
2143 |
< |
* workers; (1) cancelling all tasks; (2) interrupting lagging |
2144 |
< |
* threads (likely in external tasks, but possibly also blocked in |
2145 |
< |
* joins). Each pass repeats previous steps because of potential |
2146 |
< |
* lagging thread creation. |
2147 |
< |
*/ |
1841 |
< |
private void startTerminating() { |
1842 |
< |
for (int pass = 0; pass < 3; ++pass) { |
1843 |
< |
WorkQueue[] ws = workQueues; |
1844 |
< |
if (ws != null) { |
1845 |
< |
WorkQueue w; Thread wt; |
1846 |
< |
int n = ws.length; |
1847 |
< |
for (int j = 0; j < n; ++j) { |
1848 |
< |
if ((w = ws[j]) != null) { |
1849 |
< |
w.runState = -1; |
1850 |
< |
if (pass > 0) { |
1851 |
< |
w.cancelAll(); |
1852 |
< |
if (pass > 1 && (wt = w.owner) != null && |
1853 |
< |
!wt.isInterrupted()) { |
1854 |
< |
try { |
1855 |
< |
wt.interrupt(); |
1856 |
< |
} catch (SecurityException ignore) { |
2135 |
> |
if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) { |
2136 |
> |
for (int pass = 0; pass < 3; ++pass) { |
2137 |
> |
WorkQueue[] ws = workQueues; |
2138 |
> |
if (ws != null) { |
2139 |
> |
WorkQueue w; |
2140 |
> |
int n = ws.length; |
2141 |
> |
for (int i = 0; i < n; ++i) { |
2142 |
> |
if ((w = ws[i]) != null) { |
2143 |
> |
w.runState = -1; |
2144 |
> |
if (pass > 0) { |
2145 |
> |
w.cancelAll(); |
2146 |
> |
if (pass > 1) |
2147 |
> |
w.interruptOwner(); |
2148 |
|
} |
2149 |
|
} |
2150 |
|
} |
2151 |
< |
} |
2152 |
< |
} |
2153 |
< |
// Wake up workers parked on event queue |
2154 |
< |
int i, e; long c; Thread p; |
2155 |
< |
while ((i = ((~(e = (int)(c = ctl)) << 1) | 1) & SMASK) < n && |
2156 |
< |
(w = ws[i]) != null && |
2157 |
< |
w.eventCount == (e | INT_SIGN)) { |
2158 |
< |
long nc = ((long)(w.nextWait & E_MASK) | |
2159 |
< |
((c + AC_UNIT) & AC_MASK) | |
2160 |
< |
(c & (TC_MASK|STOP_BIT))); |
2161 |
< |
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
2162 |
< |
w.eventCount = (e + E_SEQ) & E_MASK; |
2163 |
< |
if ((p = w.parker) != null) |
2164 |
< |
U.unpark(p); |
2151 |
> |
// Wake up workers parked on event queue |
2152 |
> |
int i, e; long cc; Thread p; |
2153 |
> |
while ((e = (int)(cc = ctl) & E_MASK) != 0 && |
2154 |
> |
(i = e & SMASK) < n && |
2155 |
> |
(w = ws[i]) != null) { |
2156 |
> |
long nc = ((long)(w.nextWait & E_MASK) | |
2157 |
> |
((cc + AC_UNIT) & AC_MASK) | |
2158 |
> |
(cc & (TC_MASK|STOP_BIT))); |
2159 |
> |
if (w.eventCount == (e | INT_SIGN) && |
2160 |
> |
U.compareAndSwapLong(this, CTL, cc, nc)) { |
2161 |
> |
w.eventCount = (e + E_SEQ) & E_MASK; |
2162 |
> |
w.runState = -1; |
2163 |
> |
if ((p = w.parker) != null) |
2164 |
> |
U.unpark(p); |
2165 |
> |
} |
2166 |
> |
} |
2167 |
|
} |
2168 |
|
} |
2169 |
|
} |
2239 |
|
checkPermission(); |
2240 |
|
if (factory == null) |
2241 |
|
throw new NullPointerException(); |
2242 |
< |
if (parallelism <= 0 || parallelism > MAX_ID) |
2242 |
> |
if (parallelism <= 0 || parallelism > MAX_CAP) |
2243 |
|
throw new IllegalArgumentException(); |
2244 |
|
this.parallelism = parallelism; |
2245 |
|
this.factory = factory; |
2246 |
|
this.ueh = handler; |
2247 |
|
this.localMode = asyncMode ? FIFO_QUEUE : LIFO_QUEUE; |
1955 |
– |
this.nextPoolIndex = 1; |
2248 |
|
long np = (long)(-parallelism); // offset ctl counts |
2249 |
|
this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK); |
2250 |
< |
// initialize workQueues array with room for 2*parallelism if possible |
2251 |
< |
int n = parallelism << 1; |
2252 |
< |
if (n >= MAX_ID) |
2253 |
< |
n = MAX_ID; |
2254 |
< |
else { // See Hackers Delight, sec 3.2, where n < (1 << 16) |
2255 |
< |
n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; |
2256 |
< |
} |
1965 |
< |
this.workQueues = new WorkQueue[(n + 1) << 1]; |
1966 |
< |
ReentrantLock lck = this.lock = new ReentrantLock(); |
1967 |
< |
this.termination = lck.newCondition(); |
2250 |
> |
// Use nearest power 2 for workQueues size. See Hackers Delight sec 3.2. |
2251 |
> |
int n = parallelism - 1; |
2252 |
> |
n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; |
2253 |
> |
int size = (n + 1) << 1; // #slots = 2*#workers |
2254 |
> |
this.submitMask = size - 1; // room for max # of submit queues |
2255 |
> |
this.workQueues = new WorkQueue[size]; |
2256 |
> |
this.termination = (this.lock = new Mutex()).newCondition(); |
2257 |
|
this.stealCount = new AtomicLong(); |
2258 |
|
this.nextWorkerNumber = new AtomicInteger(); |
2259 |
+ |
int pn = poolNumberGenerator.incrementAndGet(); |
2260 |
|
StringBuilder sb = new StringBuilder("ForkJoinPool-"); |
2261 |
< |
sb.append(poolNumberGenerator.incrementAndGet()); |
2261 |
> |
sb.append(Integer.toString(pn)); |
2262 |
|
sb.append("-worker-"); |
2263 |
|
this.workerNamePrefix = sb.toString(); |
2264 |
< |
// Create initial submission queue |
2265 |
< |
WorkQueue sq = tryAddSharedQueue(0); |
2266 |
< |
if (sq != null) |
2267 |
< |
sq.growArray(false); |
2264 |
> |
lock.lock(); |
2265 |
> |
this.runState = 1; // set init flag |
2266 |
> |
lock.unlock(); |
2267 |
> |
} |
2268 |
> |
|
2269 |
> |
/** |
2270 |
> |
* Returns the common pool instance |
2271 |
> |
* |
2272 |
> |
* @return the common pool instance |
2273 |
> |
*/ |
2274 |
> |
public static ForkJoinPool commonPool() { |
2275 |
> |
ForkJoinPool p; |
2276 |
> |
return (p = commonPool) != null? p : ensureCommonPool(); |
2277 |
> |
} |
2278 |
> |
|
2279 |
> |
private static ForkJoinPool ensureCommonPool() { |
2280 |
> |
ForkJoinPool p; |
2281 |
> |
if ((p = commonPool) == null) { |
2282 |
> |
final Mutex lock = initializationLock; |
2283 |
> |
lock.lock(); |
2284 |
> |
try { |
2285 |
> |
if ((p = commonPool) == null) { |
2286 |
> |
p = commonPool = new ForkJoinPool(commonPoolParallelism, |
2287 |
> |
commonPoolFactory, |
2288 |
> |
commonPoolUEH, false); |
2289 |
> |
// use a more informative name string for workers |
2290 |
> |
p.workerNamePrefix = "ForkJoinPool.commonPool-worker-"; |
2291 |
> |
} |
2292 |
> |
} finally { |
2293 |
> |
lock.unlock(); |
2294 |
> |
} |
2295 |
> |
} |
2296 |
> |
return p; |
2297 |
|
} |
2298 |
|
|
2299 |
|
// Execution methods |
2315 |
|
* scheduled for execution |
2316 |
|
*/ |
2317 |
|
public <T> T invoke(ForkJoinTask<T> task) { |
2318 |
+ |
if (task == null) |
2319 |
+ |
throw new NullPointerException(); |
2320 |
|
doSubmit(task); |
2321 |
|
return task.join(); |
2322 |
|
} |
2330 |
|
* scheduled for execution |
2331 |
|
*/ |
2332 |
|
public void execute(ForkJoinTask<?> task) { |
2333 |
+ |
if (task == null) |
2334 |
+ |
throw new NullPointerException(); |
2335 |
|
doSubmit(task); |
2336 |
|
} |
2337 |
|
|
2349 |
|
if (task instanceof ForkJoinTask<?>) // avoid re-wrap |
2350 |
|
job = (ForkJoinTask<?>) task; |
2351 |
|
else |
2352 |
< |
job = ForkJoinTask.adapt(task, null); |
2352 |
> |
job = new ForkJoinTask.AdaptedRunnableAction(task); |
2353 |
|
doSubmit(job); |
2354 |
|
} |
2355 |
|
|
2363 |
|
* scheduled for execution |
2364 |
|
*/ |
2365 |
|
public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) { |
2366 |
+ |
if (task == null) |
2367 |
+ |
throw new NullPointerException(); |
2368 |
|
doSubmit(task); |
2369 |
|
return task; |
2370 |
|
} |
2375 |
|
* scheduled for execution |
2376 |
|
*/ |
2377 |
|
public <T> ForkJoinTask<T> submit(Callable<T> task) { |
2378 |
< |
if (task == null) |
2054 |
< |
throw new NullPointerException(); |
2055 |
< |
ForkJoinTask<T> job = ForkJoinTask.adapt(task); |
2378 |
> |
ForkJoinTask<T> job = new ForkJoinTask.AdaptedCallable<T>(task); |
2379 |
|
doSubmit(job); |
2380 |
|
return job; |
2381 |
|
} |
2386 |
|
* scheduled for execution |
2387 |
|
*/ |
2388 |
|
public <T> ForkJoinTask<T> submit(Runnable task, T result) { |
2389 |
< |
if (task == null) |
2067 |
< |
throw new NullPointerException(); |
2068 |
< |
ForkJoinTask<T> job = ForkJoinTask.adapt(task, result); |
2389 |
> |
ForkJoinTask<T> job = new ForkJoinTask.AdaptedRunnable<T>(task, result); |
2390 |
|
doSubmit(job); |
2391 |
|
return job; |
2392 |
|
} |
2403 |
|
if (task instanceof ForkJoinTask<?>) // avoid re-wrap |
2404 |
|
job = (ForkJoinTask<?>) task; |
2405 |
|
else |
2406 |
< |
job = ForkJoinTask.adapt(task, null); |
2406 |
> |
job = new ForkJoinTask.AdaptedRunnableAction(task); |
2407 |
|
doSubmit(job); |
2408 |
|
return job; |
2409 |
|
} |
2413 |
|
* @throws RejectedExecutionException {@inheritDoc} |
2414 |
|
*/ |
2415 |
|
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) { |
2416 |
< |
ArrayList<ForkJoinTask<T>> forkJoinTasks = |
2417 |
< |
new ArrayList<ForkJoinTask<T>>(tasks.size()); |
2418 |
< |
for (Callable<T> task : tasks) |
2419 |
< |
forkJoinTasks.add(ForkJoinTask.adapt(task)); |
2420 |
< |
invoke(new InvokeAll<T>(forkJoinTasks)); |
2421 |
< |
|
2416 |
> |
// In previous versions of this class, this method constructed |
2417 |
> |
// a task to run ForkJoinTask.invokeAll, but now external |
2418 |
> |
// invocation of multiple tasks is at least as efficient. |
2419 |
> |
List<ForkJoinTask<T>> fs = new ArrayList<ForkJoinTask<T>>(tasks.size()); |
2420 |
> |
// Workaround needed because method wasn't declared with |
2421 |
> |
// wildcards in return type but should have been. |
2422 |
|
@SuppressWarnings({"unchecked", "rawtypes"}) |
2423 |
< |
List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks; |
2103 |
< |
return futures; |
2104 |
< |
} |
2423 |
> |
List<Future<T>> futures = (List<Future<T>>) (List) fs; |
2424 |
|
|
2425 |
< |
static final class InvokeAll<T> extends RecursiveAction { |
2426 |
< |
final ArrayList<ForkJoinTask<T>> tasks; |
2427 |
< |
InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; } |
2428 |
< |
public void compute() { |
2429 |
< |
try { invokeAll(tasks); } |
2430 |
< |
catch (Exception ignore) {} |
2425 |
> |
boolean done = false; |
2426 |
> |
try { |
2427 |
> |
for (Callable<T> t : tasks) { |
2428 |
> |
ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t); |
2429 |
> |
doSubmit(f); |
2430 |
> |
fs.add(f); |
2431 |
> |
} |
2432 |
> |
for (ForkJoinTask<T> f : fs) |
2433 |
> |
f.quietlyJoin(); |
2434 |
> |
done = true; |
2435 |
> |
return futures; |
2436 |
> |
} finally { |
2437 |
> |
if (!done) |
2438 |
> |
for (ForkJoinTask<T> f : fs) |
2439 |
> |
f.cancel(false); |
2440 |
|
} |
2113 |
– |
private static final long serialVersionUID = -7914297376763021607L; |
2441 |
|
} |
2442 |
|
|
2443 |
|
/** |
2469 |
|
} |
2470 |
|
|
2471 |
|
/** |
2472 |
+ |
* Returns the targeted parallelism level of the common pool. |
2473 |
+ |
* |
2474 |
+ |
* @return the targeted parallelism level of the common pool |
2475 |
+ |
*/ |
2476 |
+ |
public static int getCommonPoolParallelism() { |
2477 |
+ |
return commonPoolParallelism; |
2478 |
+ |
} |
2479 |
+ |
|
2480 |
+ |
/** |
2481 |
|
* Returns the number of worker threads that have started but not |
2482 |
|
* yet terminated. The result returned by this method may differ |
2483 |
|
* from {@link #getParallelism} when threads are created to |
2511 |
|
int rc = 0; |
2512 |
|
WorkQueue[] ws; WorkQueue w; |
2513 |
|
if ((ws = workQueues) != null) { |
2514 |
< |
int n = ws.length; |
2515 |
< |
for (int i = 1; i < n; i += 2) { |
2180 |
< |
Thread.State s; ForkJoinWorkerThread wt; |
2181 |
< |
if ((w = ws[i]) != null && (wt = w.owner) != null && |
2182 |
< |
w.eventCount >= 0 && |
2183 |
< |
(s = wt.getState()) != Thread.State.BLOCKED && |
2184 |
< |
s != Thread.State.WAITING && |
2185 |
< |
s != Thread.State.TIMED_WAITING) |
2514 |
> |
for (int i = 1; i < ws.length; i += 2) { |
2515 |
> |
if ((w = ws[i]) != null && w.isApparentlyUnblocked()) |
2516 |
|
++rc; |
2517 |
|
} |
2518 |
|
} |
2561 |
|
long count = stealCount.get(); |
2562 |
|
WorkQueue[] ws; WorkQueue w; |
2563 |
|
if ((ws = workQueues) != null) { |
2564 |
< |
int n = ws.length; |
2235 |
< |
for (int i = 1; i < n; i += 2) { |
2564 |
> |
for (int i = 1; i < ws.length; i += 2) { |
2565 |
|
if ((w = ws[i]) != null) |
2566 |
|
count += w.totalSteals; |
2567 |
|
} |
2583 |
|
long count = 0; |
2584 |
|
WorkQueue[] ws; WorkQueue w; |
2585 |
|
if ((ws = workQueues) != null) { |
2586 |
< |
int n = ws.length; |
2258 |
< |
for (int i = 1; i < n; i += 2) { |
2586 |
> |
for (int i = 1; i < ws.length; i += 2) { |
2587 |
|
if ((w = ws[i]) != null) |
2588 |
|
count += w.queueSize(); |
2589 |
|
} |
2602 |
|
int count = 0; |
2603 |
|
WorkQueue[] ws; WorkQueue w; |
2604 |
|
if ((ws = workQueues) != null) { |
2605 |
< |
int n = ws.length; |
2278 |
< |
for (int i = 0; i < n; i += 2) { |
2605 |
> |
for (int i = 0; i < ws.length; i += 2) { |
2606 |
|
if ((w = ws[i]) != null) |
2607 |
|
count += w.queueSize(); |
2608 |
|
} |
2619 |
|
public boolean hasQueuedSubmissions() { |
2620 |
|
WorkQueue[] ws; WorkQueue w; |
2621 |
|
if ((ws = workQueues) != null) { |
2622 |
< |
int n = ws.length; |
2623 |
< |
for (int i = 0; i < n; i += 2) { |
2297 |
< |
if ((w = ws[i]) != null && w.queueSize() != 0) |
2622 |
> |
for (int i = 0; i < ws.length; i += 2) { |
2623 |
> |
if ((w = ws[i]) != null && !w.isEmpty()) |
2624 |
|
return true; |
2625 |
|
} |
2626 |
|
} |
2637 |
|
protected ForkJoinTask<?> pollSubmission() { |
2638 |
|
WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t; |
2639 |
|
if ((ws = workQueues) != null) { |
2640 |
< |
int n = ws.length; |
2315 |
< |
for (int i = 0; i < n; i += 2) { |
2640 |
> |
for (int i = 0; i < ws.length; i += 2) { |
2641 |
|
if ((w = ws[i]) != null && (t = w.poll()) != null) |
2642 |
|
return t; |
2643 |
|
} |
2666 |
|
int count = 0; |
2667 |
|
WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t; |
2668 |
|
if ((ws = workQueues) != null) { |
2669 |
< |
int n = ws.length; |
2345 |
< |
for (int i = 0; i < n; ++i) { |
2669 |
> |
for (int i = 0; i < ws.length; ++i) { |
2670 |
|
if ((w = ws[i]) != null) { |
2671 |
|
while ((t = w.poll()) != null) { |
2672 |
|
c.add(t); |
2686 |
|
* @return a string identifying this pool, as well as its state |
2687 |
|
*/ |
2688 |
|
public String toString() { |
2689 |
< |
long st = getStealCount(); |
2690 |
< |
long qt = getQueuedTaskCount(); |
2691 |
< |
long qs = getQueuedSubmissionCount(); |
2368 |
< |
int rc = getRunningThreadCount(); |
2369 |
< |
int pc = parallelism; |
2689 |
> |
// Use a single pass through workQueues to collect counts |
2690 |
> |
long qt = 0L, qs = 0L; int rc = 0; |
2691 |
> |
long st = stealCount.get(); |
2692 |
|
long c = ctl; |
2693 |
+ |
WorkQueue[] ws; WorkQueue w; |
2694 |
+ |
if ((ws = workQueues) != null) { |
2695 |
+ |
for (int i = 0; i < ws.length; ++i) { |
2696 |
+ |
if ((w = ws[i]) != null) { |
2697 |
+ |
int size = w.queueSize(); |
2698 |
+ |
if ((i & 1) == 0) |
2699 |
+ |
qs += size; |
2700 |
+ |
else { |
2701 |
+ |
qt += size; |
2702 |
+ |
st += w.totalSteals; |
2703 |
+ |
if (w.isApparentlyUnblocked()) |
2704 |
+ |
++rc; |
2705 |
+ |
} |
2706 |
+ |
} |
2707 |
+ |
} |
2708 |
+ |
} |
2709 |
+ |
int pc = parallelism; |
2710 |
|
int tc = pc + (short)(c >>> TC_SHIFT); |
2711 |
|
int ac = pc + (int)(c >> AC_SHIFT); |
2712 |
|
if (ac < 0) // ignore transient negative |
2729 |
|
} |
2730 |
|
|
2731 |
|
/** |
2732 |
< |
* Initiates an orderly shutdown in which previously submitted |
2733 |
< |
* tasks are executed, but no new tasks will be accepted. |
2734 |
< |
* Invocation has no additional effect if already shut down. |
2735 |
< |
* Tasks that are in the process of being submitted concurrently |
2736 |
< |
* during the course of this method may or may not be rejected. |
2732 |
> |
* Possibly initiates an orderly shutdown in which previously |
2733 |
> |
* submitted tasks are executed, but no new tasks will be |
2734 |
> |
* accepted. Invocation has no effect on execution state if this |
2735 |
> |
* is the {@link #commonPool}, and no additional effect if |
2736 |
> |
* already shut down. Tasks that are in the process of being |
2737 |
> |
* submitted concurrently during the course of this method may or |
2738 |
> |
* may not be rejected. |
2739 |
|
* |
2740 |
|
* @throws SecurityException if a security manager exists and |
2741 |
|
* the caller is not permitted to modify threads |
2744 |
|
*/ |
2745 |
|
public void shutdown() { |
2746 |
|
checkPermission(); |
2747 |
< |
enableShutdown(); |
2748 |
< |
tryTerminate(false); |
2747 |
> |
if (this != commonPool) |
2748 |
> |
tryTerminate(false, true); |
2749 |
|
} |
2750 |
|
|
2751 |
|
/** |
2752 |
< |
* Attempts to cancel and/or stop all tasks, and reject all |
2753 |
< |
* subsequently submitted tasks. Tasks that are in the process of |
2754 |
< |
* being submitted or executed concurrently during the course of |
2755 |
< |
* this method may or may not be rejected. This method cancels |
2756 |
< |
* both existing and unexecuted tasks, in order to permit |
2757 |
< |
* termination in the presence of task dependencies. So the method |
2758 |
< |
* always returns an empty list (unlike the case for some other |
2759 |
< |
* Executors). |
2752 |
> |
* Possibly attempts to cancel and/or stop all tasks, and reject |
2753 |
> |
* all subsequently submitted tasks. Invocation has no effect on |
2754 |
> |
* execution state if this is the {@link #commonPool}, and no |
2755 |
> |
* additional effect if already shut down. Otherwise, tasks that |
2756 |
> |
* are in the process of being submitted or executed concurrently |
2757 |
> |
* during the course of this method may or may not be |
2758 |
> |
* rejected. This method cancels both existing and unexecuted |
2759 |
> |
* tasks, in order to permit termination in the presence of task |
2760 |
> |
* dependencies. So the method always returns an empty list |
2761 |
> |
* (unlike the case for some other Executors). |
2762 |
|
* |
2763 |
|
* @return an empty list |
2764 |
|
* @throws SecurityException if a security manager exists and |
2768 |
|
*/ |
2769 |
|
public List<Runnable> shutdownNow() { |
2770 |
|
checkPermission(); |
2771 |
< |
enableShutdown(); |
2772 |
< |
tryTerminate(true); |
2771 |
> |
if (this != commonPool) |
2772 |
> |
tryTerminate(true, true); |
2773 |
|
return Collections.emptyList(); |
2774 |
|
} |
2775 |
|
|
2826 |
|
public boolean awaitTermination(long timeout, TimeUnit unit) |
2827 |
|
throws InterruptedException { |
2828 |
|
long nanos = unit.toNanos(timeout); |
2829 |
< |
final ReentrantLock lock = this.lock; |
2829 |
> |
final Mutex lock = this.lock; |
2830 |
|
lock.lock(); |
2831 |
|
try { |
2832 |
|
for (;;) { |
2940 |
|
ForkJoinPool p = ((t instanceof ForkJoinWorkerThread) ? |
2941 |
|
((ForkJoinWorkerThread)t).pool : null); |
2942 |
|
while (!blocker.isReleasable()) { |
2943 |
< |
if (p == null || p.tryCompensate()) { |
2943 |
> |
if (p == null || p.tryCompensate(null, blocker)) { |
2944 |
|
try { |
2945 |
|
do {} while (!blocker.isReleasable() && !blocker.block()); |
2946 |
|
} finally { |
2957 |
|
// implement RunnableFuture. |
2958 |
|
|
2959 |
|
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) { |
2960 |
< |
return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value); |
2960 |
> |
return new ForkJoinTask.AdaptedRunnable<T>(runnable, value); |
2961 |
|
} |
2962 |
|
|
2963 |
|
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) { |
2964 |
< |
return (RunnableFuture<T>) ForkJoinTask.adapt(callable); |
2964 |
> |
return new ForkJoinTask.AdaptedCallable<T>(callable); |
2965 |
|
} |
2966 |
|
|
2967 |
|
// Unsafe mechanics |
2968 |
|
private static final sun.misc.Unsafe U; |
2969 |
|
private static final long CTL; |
2627 |
– |
private static final long RUNSTATE; |
2970 |
|
private static final long PARKBLOCKER; |
2971 |
+ |
private static final int ABASE; |
2972 |
+ |
private static final int ASHIFT; |
2973 |
|
|
2974 |
|
static { |
2975 |
|
poolNumberGenerator = new AtomicInteger(); |
2976 |
+ |
nextSubmitterSeed = new AtomicInteger(0x55555555); |
2977 |
|
modifyThreadPermission = new RuntimePermission("modifyThread"); |
2978 |
|
defaultForkJoinWorkerThreadFactory = |
2979 |
|
new DefaultForkJoinWorkerThreadFactory(); |
2980 |
+ |
submitters = new ThreadSubmitter(); |
2981 |
+ |
initializationLock = new Mutex(); |
2982 |
|
int s; |
2983 |
|
try { |
2984 |
|
U = getUnsafe(); |
2985 |
|
Class<?> k = ForkJoinPool.class; |
2986 |
< |
Class<?> tk = Thread.class; |
2986 |
> |
Class<?> ak = ForkJoinTask[].class; |
2987 |
|
CTL = U.objectFieldOffset |
2988 |
|
(k.getDeclaredField("ctl")); |
2989 |
< |
RUNSTATE = U.objectFieldOffset |
2643 |
< |
(k.getDeclaredField("runState")); |
2989 |
> |
Class<?> tk = Thread.class; |
2990 |
|
PARKBLOCKER = U.objectFieldOffset |
2991 |
|
(tk.getDeclaredField("parkBlocker")); |
2992 |
+ |
ABASE = U.arrayBaseOffset(ak); |
2993 |
+ |
s = U.arrayIndexScale(ak); |
2994 |
+ |
} catch (Exception e) { |
2995 |
+ |
throw new Error(e); |
2996 |
+ |
} |
2997 |
+ |
if ((s & (s-1)) != 0) |
2998 |
+ |
throw new Error("data type scale not a power of two"); |
2999 |
+ |
ASHIFT = 31 - Integer.numberOfLeadingZeros(s); |
3000 |
+ |
|
3001 |
+ |
// Establish configuration for default pool |
3002 |
+ |
try { |
3003 |
+ |
String pp = System.getProperty(propPrefix + "parallelism"); |
3004 |
+ |
String fp = System.getProperty(propPrefix + "threadFactory"); |
3005 |
+ |
String up = System.getProperty(propPrefix + "exceptionHandler"); |
3006 |
+ |
int par; |
3007 |
+ |
if ((pp == null || (par = Integer.parseInt(pp)) <= 0)) |
3008 |
+ |
par = Runtime.getRuntime().availableProcessors(); |
3009 |
+ |
commonPoolParallelism = par; |
3010 |
+ |
if (fp != null) |
3011 |
+ |
commonPoolFactory = (ForkJoinWorkerThreadFactory) |
3012 |
+ |
ClassLoader.getSystemClassLoader().loadClass(fp).newInstance(); |
3013 |
+ |
else |
3014 |
+ |
commonPoolFactory = defaultForkJoinWorkerThreadFactory; |
3015 |
+ |
if (up != null) |
3016 |
+ |
commonPoolUEH = (Thread.UncaughtExceptionHandler) |
3017 |
+ |
ClassLoader.getSystemClassLoader().loadClass(up).newInstance(); |
3018 |
+ |
else |
3019 |
+ |
commonPoolUEH = null; |
3020 |
|
} catch (Exception e) { |
3021 |
|
throw new Error(e); |
3022 |
|
} |