6 |
|
|
7 |
|
package jsr166e; |
8 |
|
|
9 |
+ |
import java.lang.Thread.UncaughtExceptionHandler; |
10 |
|
import java.util.ArrayList; |
11 |
|
import java.util.Arrays; |
12 |
|
import java.util.Collection; |
50 |
|
* level; by default, equal to the number of available processors. The |
51 |
|
* pool attempts to maintain enough active (or available) threads by |
52 |
|
* dynamically adding, suspending, or resuming internal worker |
53 |
< |
* threads, even if some tasks are stalled waiting to join |
54 |
< |
* others. However, no such adjustments are guaranteed in the face of |
55 |
< |
* blocked IO or other unmanaged synchronization. The nested {@link |
53 |
> |
* threads, even if some tasks are stalled waiting to join others. |
54 |
> |
* However, no such adjustments are guaranteed in the face of blocked |
55 |
> |
* I/O or other unmanaged synchronization. The nested {@link |
56 |
|
* ManagedBlocker} interface enables extension of the kinds of |
57 |
|
* synchronization accommodated. |
58 |
|
* |
76 |
|
* there is little difference among choice of methods. |
77 |
|
* |
78 |
|
* <table BORDER CELLPADDING=3 CELLSPACING=1> |
79 |
+ |
* <caption>Summary of task execution methods</caption> |
80 |
|
* <tr> |
81 |
|
* <td></td> |
82 |
|
* <td ALIGN=CENTER> <b>Call from non-fork/join clients</b></td> |
83 |
|
* <td ALIGN=CENTER> <b>Call from within fork/join computations</b></td> |
84 |
|
* </tr> |
85 |
|
* <tr> |
86 |
< |
* <td> <b>Arrange async execution</td> |
86 |
> |
* <td> <b>Arrange async execution</b></td> |
87 |
|
* <td> {@link #execute(ForkJoinTask)}</td> |
88 |
|
* <td> {@link ForkJoinTask#fork}</td> |
89 |
|
* </tr> |
90 |
|
* <tr> |
91 |
< |
* <td> <b>Await and obtain result</td> |
91 |
> |
* <td> <b>Await and obtain result</b></td> |
92 |
|
* <td> {@link #invoke(ForkJoinTask)}</td> |
93 |
|
* <td> {@link ForkJoinTask#invoke}</td> |
94 |
|
* </tr> |
95 |
|
* <tr> |
96 |
< |
* <td> <b>Arrange exec and obtain Future</td> |
96 |
> |
* <td> <b>Arrange exec and obtain Future</b></td> |
97 |
|
* <td> {@link #submit(ForkJoinTask)}</td> |
98 |
|
* <td> {@link ForkJoinTask#fork} (ForkJoinTasks <em>are</em> Futures)</td> |
99 |
|
* </tr> |
100 |
|
* </table> |
101 |
|
* |
102 |
|
* <p>The common pool is by default constructed with default |
103 |
< |
* parameters, but these may be controlled by setting three {@link |
104 |
< |
* System#getProperty system properties} with prefix {@code |
105 |
< |
* java.util.concurrent.ForkJoinPool.common}: {@code parallelism} -- |
106 |
< |
* an integer greater than zero, {@code threadFactory} -- the class |
107 |
< |
* name of a {@link ForkJoinWorkerThreadFactory}, and {@code |
108 |
< |
* exceptionHandler} -- the class name of a {@link |
109 |
< |
* java.lang.Thread.UncaughtExceptionHandler |
110 |
< |
* Thread.UncaughtExceptionHandler}. Upon any error in establishing |
111 |
< |
* these settings, default parameters are used. |
103 |
> |
* parameters, but these may be controlled by setting three |
104 |
> |
* {@linkplain System#getProperty system properties}: |
105 |
> |
* <ul> |
106 |
> |
* <li>{@code java.util.concurrent.ForkJoinPool.common.parallelism} |
107 |
> |
* - the parallelism level, a non-negative integer |
108 |
> |
* <li>{@code java.util.concurrent.ForkJoinPool.common.threadFactory} |
109 |
> |
* - the class name of a {@link ForkJoinWorkerThreadFactory} |
110 |
> |
* <li>{@code java.util.concurrent.ForkJoinPool.common.exceptionHandler} |
111 |
> |
* - the class name of a {@link UncaughtExceptionHandler} |
112 |
> |
* </ul> |
113 |
> |
* The system class loader is used to load these classes. |
114 |
> |
* Upon any error in establishing these settings, default parameters |
115 |
> |
* are used. It is possible to disable or limit the use of threads in |
116 |
> |
* the common pool by setting the parallelism property to zero, and/or |
117 |
> |
* using a factory that may return {@code null}. |
118 |
|
* |
119 |
|
* <p><b>Implementation notes</b>: This implementation restricts the |
120 |
|
* maximum number of running threads to 32767. Attempts to create |
160 |
|
* (http://research.sun.com/scalable/pubs/index.html) and |
161 |
|
* "Idempotent work stealing" by Michael, Saraswat, and Vechev, |
162 |
|
* PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186). |
163 |
< |
* The main differences ultimately stem from GC requirements that |
164 |
< |
* we null out taken slots as soon as we can, to maintain as small |
165 |
< |
* a footprint as possible even in programs generating huge |
166 |
< |
* numbers of tasks. To accomplish this, we shift the CAS |
167 |
< |
* arbitrating pop vs poll (steal) from being on the indices |
168 |
< |
* ("base" and "top") to the slots themselves. So, both a |
169 |
< |
* successful pop and poll mainly entail a CAS of a slot from |
170 |
< |
* non-null to null. Because we rely on CASes of references, we |
171 |
< |
* do not need tag bits on base or top. They are simple ints as |
172 |
< |
* used in any circular array-based queue (see for example |
173 |
< |
* ArrayDeque). Updates to the indices must still be ordered in a |
174 |
< |
* way that guarantees that top == base means the queue is empty, |
175 |
< |
* but otherwise may err on the side of possibly making the queue |
176 |
< |
* appear nonempty when a push, pop, or poll have not fully |
177 |
< |
* committed. Note that this means that the poll operation, |
178 |
< |
* considered individually, is not wait-free. One thief cannot |
179 |
< |
* successfully continue until another in-progress one (or, if |
180 |
< |
* previously empty, a push) completes. However, in the |
181 |
< |
* aggregate, we ensure at least probabilistic non-blockingness. |
182 |
< |
* If an attempted steal fails, a thief always chooses a different |
183 |
< |
* random victim target to try next. So, in order for one thief to |
184 |
< |
* progress, it suffices for any in-progress poll or new push on |
185 |
< |
* any empty queue to complete. (This is why we normally use |
186 |
< |
* method pollAt and its variants that try once at the apparent |
187 |
< |
* base index, else consider alternative actions, rather than |
188 |
< |
* method poll.) |
163 |
> |
* See also "Correct and Efficient Work-Stealing for Weak Memory |
164 |
> |
* Models" by Le, Pop, Cohen, and Nardelli, PPoPP 2013 |
165 |
> |
* (http://www.di.ens.fr/~zappa/readings/ppopp13.pdf) for an |
166 |
> |
* analysis of memory ordering (atomic, volatile etc) issues. The |
167 |
> |
* main differences ultimately stem from GC requirements that we |
168 |
> |
* null out taken slots as soon as we can, to maintain as small a |
169 |
> |
* footprint as possible even in programs generating huge numbers |
170 |
> |
* of tasks. To accomplish this, we shift the CAS arbitrating pop |
171 |
> |
* vs poll (steal) from being on the indices ("base" and "top") to |
172 |
> |
* the slots themselves. So, both a successful pop and poll |
173 |
> |
* mainly entail a CAS of a slot from non-null to null. Because |
174 |
> |
* we rely on CASes of references, we do not need tag bits on base |
175 |
> |
* or top. They are simple ints as used in any circular |
176 |
> |
* array-based queue (see for example ArrayDeque). Updates to the |
177 |
> |
* indices must still be ordered in a way that guarantees that top |
178 |
> |
* == base means the queue is empty, but otherwise may err on the |
179 |
> |
* side of possibly making the queue appear nonempty when a push, |
180 |
> |
* pop, or poll have not fully committed. Note that this means |
181 |
> |
* that the poll operation, considered individually, is not |
182 |
> |
* wait-free. One thief cannot successfully continue until another |
183 |
> |
* in-progress one (or, if previously empty, a push) completes. |
184 |
> |
* However, in the aggregate, we ensure at least probabilistic |
185 |
> |
* non-blockingness. If an attempted steal fails, a thief always |
186 |
> |
* chooses a different random victim target to try next. So, in |
187 |
> |
* order for one thief to progress, it suffices for any |
188 |
> |
* in-progress poll or new push on any empty queue to |
189 |
> |
* complete. (This is why we normally use method pollAt and its |
190 |
> |
* variants that try once at the apparent base index, else |
191 |
> |
* consider alternative actions, rather than method poll.) |
192 |
|
* |
193 |
|
* This approach also enables support of a user mode in which local |
194 |
|
* task processing is in FIFO, not LIFO order, simply by using |
207 |
|
* for work-stealing (this would contaminate lifo/fifo |
208 |
|
* processing). Instead, we randomly associate submission queues |
209 |
|
* with submitting threads, using a form of hashing. The |
210 |
< |
* ThreadLocal Submitter class contains a value initially used as |
211 |
< |
* a hash code for choosing existing queues, but may be randomly |
212 |
< |
* repositioned upon contention with other submitters. In |
213 |
< |
* essence, submitters act like workers except that they are |
214 |
< |
* restricted to executing local tasks that they submitted (or in |
215 |
< |
* the case of CountedCompleters, others with the same root task). |
216 |
< |
* However, because most shared/external queue operations are more |
217 |
< |
* expensive than internal, and because, at steady state, external |
218 |
< |
* submitters will compete for CPU with workers, ForkJoinTask.join |
219 |
< |
* and related methods disable them from repeatedly helping to |
220 |
< |
* process tasks if all workers are active. Insertion of tasks in |
221 |
< |
* shared mode requires a lock (mainly to protect in the case of |
210 |
> |
* Submitter probe value serves as a hash code for |
211 |
> |
* choosing existing queues, and may be randomly repositioned upon |
212 |
> |
* contention with other submitters. In essence, submitters act |
213 |
> |
* like workers except that they are restricted to executing local |
214 |
> |
* tasks that they submitted (or in the case of CountedCompleters, |
215 |
> |
* others with the same root task). However, because most |
216 |
> |
* shared/external queue operations are more expensive than |
217 |
> |
* internal, and because, at steady state, external submitters |
218 |
> |
* will compete for CPU with workers, ForkJoinTask.join and |
219 |
> |
* related methods disable them from repeatedly helping to process |
220 |
> |
* tasks if all workers are active. Insertion of tasks in shared |
221 |
> |
* mode requires a lock (mainly to protect in the case of |
222 |
|
* resizing) but we use only a simple spinlock (using bits in |
223 |
|
* field qlock), because submitters encountering a busy queue move |
224 |
|
* on to try or create other queues -- they block only when |
308 |
|
* has not yet entered the wait queue. We solve this by requiring |
309 |
|
* a full sweep of all workers (via repeated calls to method |
310 |
|
* scan()) both before and after a newly waiting worker is added |
311 |
< |
* to the wait queue. During a rescan, the worker might release |
312 |
< |
* some other queued worker rather than itself, which has the same |
313 |
< |
* net effect. Because enqueued workers may actually be rescanning |
314 |
< |
* rather than waiting, we set and clear the "parker" field of |
315 |
< |
* WorkQueues to reduce unnecessary calls to unpark. (This |
316 |
< |
* requires a secondary recheck to avoid missed signals.) Note |
317 |
< |
* the unusual conventions about Thread.interrupts surrounding |
318 |
< |
* parking and other blocking: Because interrupts are used solely |
319 |
< |
* to alert threads to check termination, which is checked anyway |
320 |
< |
* upon blocking, we clear status (using Thread.interrupted) |
321 |
< |
* before any call to park, so that park does not immediately |
311 |
< |
* return due to status being set via some other unrelated call to |
312 |
< |
* interrupt in user code. |
311 |
> |
* to the wait queue. Because enqueued workers may actually be |
312 |
> |
* rescanning rather than waiting, we set and clear the "parker" |
313 |
> |
* field of WorkQueues to reduce unnecessary calls to unpark. |
314 |
> |
* (This requires a secondary recheck to avoid missed signals.) |
315 |
> |
* Note the unusual conventions about Thread.interrupts |
316 |
> |
* surrounding parking and other blocking: Because interrupts are |
317 |
> |
* used solely to alert threads to check termination, which is |
318 |
> |
* checked anyway upon blocking, we clear status (using |
319 |
> |
* Thread.interrupted) before any call to park, so that park does |
320 |
> |
* not immediately return due to status being set via some other |
321 |
> |
* unrelated call to interrupt in user code. |
322 |
|
* |
323 |
|
* Signalling. We create or wake up workers only when there |
324 |
|
* appears to be at least one task they might be able to find and |
325 |
< |
* execute. However, many other threads may notice the same task |
326 |
< |
* and each signal to wake up a thread that might take it. So in |
327 |
< |
* general, pools will be over-signalled. When a submission is |
328 |
< |
* added or another worker adds a task to a queue that has fewer |
329 |
< |
* than two tasks, they signal waiting workers (or trigger |
330 |
< |
* creation of new ones if fewer than the given parallelism level |
331 |
< |
* -- signalWork), and may leave a hint to the unparked worker to |
332 |
< |
* help signal others upon wakeup). These primary signals are |
324 |
< |
* buttressed by others (see method helpSignal) whenever other |
325 |
< |
* threads scan for work or do not have a task to process. On |
326 |
< |
* most platforms, signalling (unpark) overhead time is noticeably |
325 |
> |
* execute. When a submission is added or another worker adds a |
326 |
> |
* task to a queue that has fewer than two tasks, they signal |
327 |
> |
* waiting workers (or trigger creation of new ones if fewer than |
328 |
> |
* the given parallelism level -- signalWork). These primary |
329 |
> |
* signals are buttressed by others whenever other threads remove |
330 |
> |
* a task from a queue and notice that there are other tasks there |
331 |
> |
* as well. So in general, pools will be over-signalled. On most |
332 |
> |
* platforms, signalling (unpark) overhead time is noticeably |
333 |
|
* long, and the time between signalling a thread and it actually |
334 |
|
* making progress can be very noticeably long, so it is worth |
335 |
|
* offloading these delays from critical paths as much as |
336 |
< |
* possible. |
336 |
> |
* possible. Additionally, workers spin-down gradually, by staying |
337 |
> |
* alive so long as they see the ctl state changing. Similar |
338 |
> |
* stability-sensing techniques are also used before blocking in |
339 |
> |
* awaitJoin and helpComplete. |
340 |
|
* |
341 |
|
* Trimming workers. To release resources after periods of lack of |
342 |
|
* use, a worker starting to wait when the pool is quiescent will |
449 |
|
* Common Pool |
450 |
|
* =========== |
451 |
|
* |
452 |
< |
* The static commonPool always exists after static |
452 |
> |
* The static common pool always exists after static |
453 |
|
* initialization. Since it (or any other created pool) need |
454 |
|
* never be used, we minimize initial construction overhead and |
455 |
|
* footprint to the setup of about a dozen fields, with no nested |
457 |
|
* fullExternalPush during the first submission to the pool. |
458 |
|
* |
459 |
|
* When external threads submit to the common pool, they can |
460 |
< |
* perform some subtask processing (see externalHelpJoin and |
461 |
< |
* related methods). We do not need to record whether these |
460 |
> |
* perform subtask processing (see externalHelpJoin and related |
461 |
> |
* methods). This caller-helps policy makes it sensible to set |
462 |
> |
* common pool parallelism level to one (or more) less than the |
463 |
> |
* total number of available cores, or even zero for pure |
464 |
> |
* caller-runs. We do not need to record whether external |
465 |
|
* submissions are to the common pool -- if not, externalHelpJoin |
466 |
|
* returns quickly (at the most helping to signal some common pool |
467 |
|
* workers). These submitters would otherwise be blocked waiting |
530 |
|
* Returns a new worker thread operating in the given pool. |
531 |
|
* |
532 |
|
* @param pool the pool this thread works in |
533 |
+ |
* @return the new worker thread |
534 |
|
* @throws NullPointerException if the pool is null |
535 |
|
*/ |
536 |
|
public ForkJoinWorkerThread newThread(ForkJoinPool pool); |
548 |
|
} |
549 |
|
|
550 |
|
/** |
538 |
– |
* Per-thread records for threads that submit to pools. Currently |
539 |
– |
* holds only pseudo-random seed / index that is used to choose |
540 |
– |
* submission queues in method externalPush. In the future, this may |
541 |
– |
* also incorporate a means to implement different task rejection |
542 |
– |
* and resubmission policies. |
543 |
– |
* |
544 |
– |
* Seeds for submitters and workers/workQueues work in basically |
545 |
– |
* the same way but are initialized and updated using slightly |
546 |
– |
* different mechanics. Both are initialized using the same |
547 |
– |
* approach as in class ThreadLocal, where successive values are |
548 |
– |
* unlikely to collide with previous values. Seeds are then |
549 |
– |
* randomly modified upon collisions using xorshifts, which |
550 |
– |
* requires a non-zero seed. |
551 |
– |
*/ |
552 |
– |
static final class Submitter { |
553 |
– |
int seed; |
554 |
– |
Submitter(int s) { seed = s; } |
555 |
– |
} |
556 |
– |
|
557 |
– |
/** |
551 |
|
* Class for artificial tasks that are used to replace the target |
552 |
|
* of local joins if they are removed from an interior queue slot |
553 |
|
* in WorkQueue.tryRemoveAndExec. We don't need the proxy to |
606 |
|
* do not want multiple WorkQueue instances or multiple queue |
607 |
|
* arrays sharing cache lines. (It would be best for queue objects |
608 |
|
* and their arrays to share, but there is nothing available to |
609 |
< |
* help arrange that). Unfortunately, because they are recorded |
610 |
< |
* in a common array, WorkQueue instances are often moved to be |
618 |
< |
* adjacent by garbage collectors. To reduce impact, we use field |
619 |
< |
* padding that works OK on common platforms; this effectively |
620 |
< |
* trades off slightly slower average field access for the sake of |
621 |
< |
* avoiding really bad worst-case access. (Until better JVM |
622 |
< |
* support is in place, this padding is dependent on transient |
623 |
< |
* properties of JVM field layout rules.) We also take care in |
624 |
< |
* allocating, sizing and resizing the array. Non-shared queue |
625 |
< |
* arrays are initialized by workers before use. Others are |
626 |
< |
* allocated on first use. |
609 |
> |
* help arrange that). The @Contended annotation alerts JVMs to |
610 |
> |
* try to keep instances apart. |
611 |
|
*/ |
612 |
|
static final class WorkQueue { |
613 |
|
/** |
633 |
|
// Heuristic padding to ameliorate unfortunate memory placements |
634 |
|
volatile long pad00, pad01, pad02, pad03, pad04, pad05, pad06; |
635 |
|
|
652 |
– |
int seed; // for random scanning; initialize nonzero |
636 |
|
volatile int eventCount; // encoded inactivation count; < 0 if inactive |
637 |
|
int nextWait; // encoded record of next event waiter |
655 |
– |
int hint; // steal or signal hint (index) |
656 |
– |
int poolIndex; // index of this queue in pool (or 0) |
657 |
– |
final int mode; // 0: lifo, > 0: fifo, < 0: shared |
638 |
|
int nsteals; // number of steals |
639 |
+ |
int hint; // steal index hint |
640 |
+ |
short poolIndex; // index of this queue in pool |
641 |
+ |
final short mode; // 0: lifo, > 0: fifo, < 0: shared |
642 |
|
volatile int qlock; // 1: locked, -1: terminate; else 0 |
643 |
|
volatile int base; // index of next slot for poll |
644 |
|
int top; // index of next slot for push |
656 |
|
int seed) { |
657 |
|
this.pool = pool; |
658 |
|
this.owner = owner; |
659 |
< |
this.mode = mode; |
660 |
< |
this.seed = seed; |
659 |
> |
this.mode = (short)mode; |
660 |
> |
this.hint = seed; // store initial seed for runWorker |
661 |
|
// Place indices in the center of array (that is not yet allocated) |
662 |
|
base = top = INITIAL_QUEUE_CAPACITY >>> 1; |
663 |
|
} |
670 |
|
return (n >= 0) ? 0 : -n; // ignore transient negative |
671 |
|
} |
672 |
|
|
673 |
< |
/** |
673 |
> |
/** |
674 |
|
* Provides a more accurate estimate of whether this queue has |
675 |
|
* any tasks than does queueSize, by checking whether a |
676 |
|
* near-empty queue has at least one unclaimed task. |
691 |
|
* shared-queue version is embedded in method externalPush.) |
692 |
|
* |
693 |
|
* @param task the task. Caller must ensure non-null. |
694 |
< |
* @throw RejectedExecutionException if array cannot be resized |
694 |
> |
* @throws RejectedExecutionException if array cannot be resized |
695 |
|
*/ |
696 |
|
final void push(ForkJoinTask<?> task) { |
697 |
|
ForkJoinTask<?>[] a; ForkJoinPool p; |
698 |
< |
int s = top, m, n; |
698 |
> |
int s = top, n; |
699 |
|
if ((a = array) != null) { // ignore if queue removed |
700 |
< |
int j = (((m = a.length - 1) & s) << ASHIFT) + ABASE; |
701 |
< |
U.putOrderedObject(a, j, task); |
702 |
< |
if ((n = (top = s + 1) - base) <= 2) { |
703 |
< |
if ((p = pool) != null) |
721 |
< |
p.signalWork(this); |
722 |
< |
} |
700 |
> |
int m = a.length - 1; |
701 |
> |
U.putOrderedObject(a, ((m & s) << ASHIFT) + ABASE, task); |
702 |
> |
if ((n = (top = s + 1) - base) <= 2) |
703 |
> |
(p = pool).signalWork(p.workQueues, this); |
704 |
|
else if (n >= m) |
705 |
|
growArray(); |
706 |
|
} |
707 |
|
} |
708 |
|
|
709 |
< |
/** |
709 |
> |
/** |
710 |
|
* Initializes or doubles the capacity of array. Call either |
711 |
|
* by owner or with lock held -- it is OK for base, but not |
712 |
|
* top, to move while resizings are in progress. |
764 |
|
if ((a = array) != null) { |
765 |
|
int j = (((a.length - 1) & b) << ASHIFT) + ABASE; |
766 |
|
if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) != null && |
767 |
< |
base == b && |
768 |
< |
U.compareAndSwapObject(a, j, t, null)) { |
788 |
< |
base = b + 1; |
767 |
> |
base == b && U.compareAndSwapObject(a, j, t, null)) { |
768 |
> |
U.putOrderedInt(this, QBASE, b + 1); |
769 |
|
return t; |
770 |
|
} |
771 |
|
} |
781 |
|
int j = (((a.length - 1) & b) << ASHIFT) + ABASE; |
782 |
|
t = (ForkJoinTask<?>)U.getObjectVolatile(a, j); |
783 |
|
if (t != null) { |
784 |
< |
if (base == b && |
785 |
< |
U.compareAndSwapObject(a, j, t, null)) { |
806 |
< |
base = b + 1; |
784 |
> |
if (U.compareAndSwapObject(a, j, t, null)) { |
785 |
> |
U.putOrderedInt(this, QBASE, b + 1); |
786 |
|
return t; |
787 |
|
} |
788 |
|
} |
839 |
|
ForkJoinTask.cancelIgnoringExceptions(t); |
840 |
|
} |
841 |
|
|
863 |
– |
/** |
864 |
– |
* Computes next value for random probes. Scans don't require |
865 |
– |
* a very high quality generator, but also not a crummy one. |
866 |
– |
* Marsaglia xor-shift is cheap and works well enough. Note: |
867 |
– |
* This is manually inlined in its usages in ForkJoinPool to |
868 |
– |
* avoid writes inside busy scan loops. |
869 |
– |
*/ |
870 |
– |
final int nextSeed() { |
871 |
– |
int r = seed; |
872 |
– |
r ^= r << 13; |
873 |
– |
r ^= r >>> 17; |
874 |
– |
return seed = r ^= r << 5; |
875 |
– |
} |
876 |
– |
|
842 |
|
// Specialized execution methods |
843 |
|
|
844 |
|
/** |
845 |
< |
* Pops and runs tasks until empty. |
845 |
> |
* Polls and runs tasks until empty. |
846 |
|
*/ |
847 |
< |
private void popAndExecAll() { |
848 |
< |
// A bit faster than repeated pop calls |
849 |
< |
ForkJoinTask<?>[] a; int m, s; long j; ForkJoinTask<?> t; |
885 |
< |
while ((a = array) != null && (m = a.length - 1) >= 0 && |
886 |
< |
(s = top - 1) - base >= 0 && |
887 |
< |
(t = ((ForkJoinTask<?>) |
888 |
< |
U.getObject(a, j = ((m & s) << ASHIFT) + ABASE))) |
889 |
< |
!= null) { |
890 |
< |
if (U.compareAndSwapObject(a, j, t, null)) { |
891 |
< |
top = s; |
892 |
< |
t.doExec(); |
893 |
< |
} |
894 |
< |
} |
847 |
> |
final void pollAndExecAll() { |
848 |
> |
for (ForkJoinTask<?> t; (t = poll()) != null;) |
849 |
> |
t.doExec(); |
850 |
|
} |
851 |
|
|
852 |
|
/** |
853 |
< |
* Polls and runs tasks until empty. |
853 |
> |
* Executes a top-level task and any local tasks remaining |
854 |
> |
* after execution. |
855 |
|
*/ |
856 |
< |
private void pollAndExecAll() { |
857 |
< |
for (ForkJoinTask<?> t; (t = poll()) != null;) |
858 |
< |
t.doExec(); |
856 |
> |
final void runTask(ForkJoinTask<?> task) { |
857 |
> |
if ((currentSteal = task) != null) { |
858 |
> |
task.doExec(); |
859 |
> |
ForkJoinTask<?>[] a = array; |
860 |
> |
int md = mode; |
861 |
> |
++nsteals; |
862 |
> |
currentSteal = null; |
863 |
> |
if (md != 0) |
864 |
> |
pollAndExecAll(); |
865 |
> |
else if (a != null) { |
866 |
> |
int s, m = a.length - 1; |
867 |
> |
while ((s = top - 1) - base >= 0) { |
868 |
> |
long i = ((m & s) << ASHIFT) + ABASE; |
869 |
> |
ForkJoinTask<?> t = (ForkJoinTask<?>)U.getObject(a, i); |
870 |
> |
if (t == null) |
871 |
> |
break; |
872 |
> |
if (U.compareAndSwapObject(a, i, t, null)) { |
873 |
> |
top = s; |
874 |
> |
t.doExec(); |
875 |
> |
} |
876 |
> |
} |
877 |
> |
} |
878 |
> |
} |
879 |
|
} |
880 |
|
|
881 |
|
/** |
883 |
|
* or any other cancelled task. Returns (true) on any CAS |
884 |
|
* or consistency check failure so caller can retry. |
885 |
|
* |
886 |
< |
* @return false if no progress can be made, else true; |
886 |
> |
* @return false if no progress can be made, else true |
887 |
|
*/ |
888 |
|
final boolean tryRemoveAndExec(ForkJoinTask<?> task) { |
889 |
< |
boolean stat = true, removed = false, empty = true; |
889 |
> |
boolean stat; |
890 |
|
ForkJoinTask<?>[] a; int m, s, b, n; |
891 |
< |
if ((a = array) != null && (m = a.length - 1) >= 0 && |
891 |
> |
if (task != null && (a = array) != null && (m = a.length - 1) >= 0 && |
892 |
|
(n = (s = top) - (b = base)) > 0) { |
893 |
+ |
boolean removed = false, empty = true; |
894 |
+ |
stat = true; |
895 |
|
for (ForkJoinTask<?> t;;) { // traverse from s to b |
896 |
< |
int j = ((--s & m) << ASHIFT) + ABASE; |
897 |
< |
t = (ForkJoinTask<?>)U.getObjectVolatile(a, j); |
896 |
> |
long j = ((--s & m) << ASHIFT) + ABASE; |
897 |
> |
t = (ForkJoinTask<?>)U.getObject(a, j); |
898 |
|
if (t == null) // inconsistent length |
899 |
|
break; |
900 |
|
else if (t == task) { |
922 |
|
break; |
923 |
|
} |
924 |
|
} |
925 |
+ |
if (removed) |
926 |
+ |
task.doExec(); |
927 |
|
} |
928 |
< |
if (removed) |
929 |
< |
task.doExec(); |
928 |
> |
else |
929 |
> |
stat = false; |
930 |
|
return stat; |
931 |
|
} |
932 |
|
|
933 |
|
/** |
934 |
< |
* Polls for and executes the given task or any other task in |
935 |
< |
* its CountedCompleter computation |
934 |
> |
* Tries to poll for and execute the given task or any other |
935 |
> |
* task in its CountedCompleter computation. |
936 |
|
*/ |
937 |
< |
final boolean pollAndExecCC(ForkJoinTask<?> root) { |
938 |
< |
ForkJoinTask<?>[] a; int b; Object o; |
939 |
< |
outer: while ((b = base) - top < 0 && (a = array) != null) { |
937 |
> |
final boolean pollAndExecCC(CountedCompleter<?> root) { |
938 |
> |
ForkJoinTask<?>[] a; int b; Object o; CountedCompleter<?> t, r; |
939 |
> |
if ((b = base) - top < 0 && (a = array) != null) { |
940 |
|
long j = (((a.length - 1) & b) << ASHIFT) + ABASE; |
941 |
< |
if ((o = U.getObject(a, j)) == null || |
942 |
< |
!(o instanceof CountedCompleter)) |
943 |
< |
break; |
944 |
< |
for (CountedCompleter<?> t = (CountedCompleter<?>)o, r = t;;) { |
945 |
< |
if (r == root) { |
946 |
< |
if (base == b && |
947 |
< |
U.compareAndSwapObject(a, j, t, null)) { |
948 |
< |
base = b + 1; |
949 |
< |
t.doExec(); |
941 |
> |
if ((o = U.getObjectVolatile(a, j)) == null) |
942 |
> |
return true; // retry |
943 |
> |
if (o instanceof CountedCompleter) { |
944 |
> |
for (t = (CountedCompleter<?>)o, r = t;;) { |
945 |
> |
if (r == root) { |
946 |
> |
if (base == b && |
947 |
> |
U.compareAndSwapObject(a, j, t, null)) { |
948 |
> |
U.putOrderedInt(this, QBASE, b + 1); |
949 |
> |
t.doExec(); |
950 |
> |
} |
951 |
|
return true; |
952 |
|
} |
953 |
< |
else |
954 |
< |
break; // restart |
953 |
> |
else if ((r = r.completer) == null) |
954 |
> |
break; // not part of root computation |
955 |
|
} |
975 |
– |
if ((r = r.completer) == null) |
976 |
– |
break outer; // not part of root computation |
956 |
|
} |
957 |
|
} |
958 |
|
return false; |
959 |
|
} |
960 |
|
|
961 |
|
/** |
962 |
< |
* Executes a top-level task and any local tasks remaining |
963 |
< |
* after execution. |
962 |
> |
* Tries to pop and execute the given task or any other task |
963 |
> |
* in its CountedCompleter computation. |
964 |
|
*/ |
965 |
< |
final void runTask(ForkJoinTask<?> t) { |
966 |
< |
if (t != null) { |
967 |
< |
(currentSteal = t).doExec(); |
968 |
< |
currentSteal = null; |
969 |
< |
if (base - top < 0) { // process remaining local tasks |
970 |
< |
if (mode == 0) |
971 |
< |
popAndExecAll(); |
972 |
< |
else |
973 |
< |
pollAndExecAll(); |
965 |
> |
final boolean externalPopAndExecCC(CountedCompleter<?> root) { |
966 |
> |
ForkJoinTask<?>[] a; int s; Object o; CountedCompleter<?> t, r; |
967 |
> |
if (base - (s = top) < 0 && (a = array) != null) { |
968 |
> |
long j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE; |
969 |
> |
if ((o = U.getObject(a, j)) instanceof CountedCompleter) { |
970 |
> |
for (t = (CountedCompleter<?>)o, r = t;;) { |
971 |
> |
if (r == root) { |
972 |
> |
if (U.compareAndSwapInt(this, QLOCK, 0, 1)) { |
973 |
> |
if (top == s && array == a && |
974 |
> |
U.compareAndSwapObject(a, j, t, null)) { |
975 |
> |
top = s - 1; |
976 |
> |
qlock = 0; |
977 |
> |
t.doExec(); |
978 |
> |
} |
979 |
> |
else |
980 |
> |
qlock = 0; |
981 |
> |
} |
982 |
> |
return true; |
983 |
> |
} |
984 |
> |
else if ((r = r.completer) == null) |
985 |
> |
break; |
986 |
> |
} |
987 |
|
} |
996 |
– |
++nsteals; |
997 |
– |
hint = -1; |
988 |
|
} |
989 |
+ |
return false; |
990 |
|
} |
991 |
|
|
992 |
|
/** |
993 |
< |
* Executes a non-top-level (stolen) task. |
993 |
> |
* Internal version |
994 |
|
*/ |
995 |
< |
final void runSubtask(ForkJoinTask<?> t) { |
996 |
< |
if (t != null) { |
997 |
< |
ForkJoinTask<?> ps = currentSteal; |
998 |
< |
(currentSteal = t).doExec(); |
999 |
< |
currentSteal = ps; |
995 |
> |
final boolean internalPopAndExecCC(CountedCompleter<?> root) { |
996 |
> |
ForkJoinTask<?>[] a; int s; Object o; CountedCompleter<?> t, r; |
997 |
> |
if (base - (s = top) < 0 && (a = array) != null) { |
998 |
> |
long j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE; |
999 |
> |
if ((o = U.getObject(a, j)) instanceof CountedCompleter) { |
1000 |
> |
for (t = (CountedCompleter<?>)o, r = t;;) { |
1001 |
> |
if (r == root) { |
1002 |
> |
if (U.compareAndSwapObject(a, j, t, null)) { |
1003 |
> |
top = s - 1; |
1004 |
> |
t.doExec(); |
1005 |
> |
} |
1006 |
> |
return true; |
1007 |
> |
} |
1008 |
> |
else if ((r = r.completer) == null) |
1009 |
> |
break; |
1010 |
> |
} |
1011 |
> |
} |
1012 |
|
} |
1013 |
+ |
return false; |
1014 |
|
} |
1015 |
|
|
1016 |
|
/** |
1025 |
|
s != Thread.State.TIMED_WAITING); |
1026 |
|
} |
1027 |
|
|
1024 |
– |
/** |
1025 |
– |
* If this owned and is not already interrupted, try to |
1026 |
– |
* interrupt and/or unpark, ignoring exceptions. |
1027 |
– |
*/ |
1028 |
– |
final void interruptOwner() { |
1029 |
– |
Thread wt, p; |
1030 |
– |
if ((wt = owner) != null && !wt.isInterrupted()) { |
1031 |
– |
try { |
1032 |
– |
wt.interrupt(); |
1033 |
– |
} catch (SecurityException ignore) { |
1034 |
– |
} |
1035 |
– |
} |
1036 |
– |
if ((p = parker) != null) |
1037 |
– |
U.unpark(p); |
1038 |
– |
} |
1039 |
– |
|
1028 |
|
// Unsafe mechanics |
1029 |
|
private static final sun.misc.Unsafe U; |
1030 |
+ |
private static final long QBASE; |
1031 |
|
private static final long QLOCK; |
1032 |
|
private static final int ABASE; |
1033 |
|
private static final int ASHIFT; |
1034 |
|
static { |
1046 |
– |
int s; |
1035 |
|
try { |
1036 |
|
U = getUnsafe(); |
1037 |
|
Class<?> k = WorkQueue.class; |
1038 |
|
Class<?> ak = ForkJoinTask[].class; |
1039 |
+ |
QBASE = U.objectFieldOffset |
1040 |
+ |
(k.getDeclaredField("base")); |
1041 |
|
QLOCK = U.objectFieldOffset |
1042 |
|
(k.getDeclaredField("qlock")); |
1043 |
|
ABASE = U.arrayBaseOffset(ak); |
1044 |
< |
s = U.arrayIndexScale(ak); |
1044 |
> |
int scale = U.arrayIndexScale(ak); |
1045 |
> |
if ((scale & (scale - 1)) != 0) |
1046 |
> |
throw new Error("data type scale not a power of two"); |
1047 |
> |
ASHIFT = 31 - Integer.numberOfLeadingZeros(scale); |
1048 |
|
} catch (Exception e) { |
1049 |
|
throw new Error(e); |
1050 |
|
} |
1058 |
– |
if ((s & (s-1)) != 0) |
1059 |
– |
throw new Error("data type scale not a power of two"); |
1060 |
– |
ASHIFT = 31 - Integer.numberOfLeadingZeros(s); |
1051 |
|
} |
1052 |
|
} |
1053 |
|
|
1054 |
|
// static fields (initialized in static initializer below) |
1055 |
|
|
1056 |
|
/** |
1067 |
– |
* Creates a new ForkJoinWorkerThread. This factory is used unless |
1068 |
– |
* overridden in ForkJoinPool constructors. |
1069 |
– |
*/ |
1070 |
– |
public static final ForkJoinWorkerThreadFactory |
1071 |
– |
defaultForkJoinWorkerThreadFactory; |
1072 |
– |
|
1073 |
– |
/** |
1057 |
|
* Per-thread submission bookkeeping. Shared across all pools |
1058 |
|
* to reduce ThreadLocal pollution and because random motion |
1059 |
|
* to avoid contention in one pool is likely to hold for others. |
1063 |
|
static final ThreadLocal<Submitter> submitters; |
1064 |
|
|
1065 |
|
/** |
1066 |
+ |
* Creates a new ForkJoinWorkerThread. This factory is used unless |
1067 |
+ |
* overridden in ForkJoinPool constructors. |
1068 |
+ |
*/ |
1069 |
+ |
public static final ForkJoinWorkerThreadFactory |
1070 |
+ |
defaultForkJoinWorkerThreadFactory; |
1071 |
+ |
|
1072 |
+ |
/** |
1073 |
|
* Permission required for callers of methods that may start or |
1074 |
|
* kill threads. |
1075 |
|
*/ |
1081 |
|
* to paranoically avoid potential initialization circularities |
1082 |
|
* as well as to simplify generated code. |
1083 |
|
*/ |
1084 |
< |
static final ForkJoinPool commonPool; |
1084 |
> |
static final ForkJoinPool common; |
1085 |
|
|
1086 |
|
/** |
1087 |
< |
* Common pool parallelism. Must equal commonPool.parallelism. |
1087 |
> |
* Common pool parallelism. To allow simpler use and management |
1088 |
> |
* when common pool threads are disabled, we allow the underlying |
1089 |
> |
* common.parallelism field to be zero, but in that case still report |
1090 |
> |
* parallelism as 1 to reflect resulting caller-runs mechanics. |
1091 |
|
*/ |
1092 |
< |
static final int commonPoolParallelism; |
1092 |
> |
static final int commonParallelism; |
1093 |
|
|
1094 |
|
/** |
1095 |
|
* Sequence number for creating workerNamePrefix. |
1097 |
|
private static int poolNumberSequence; |
1098 |
|
|
1099 |
|
/** |
1100 |
< |
* Return the next sequence number. We don't expect this to |
1101 |
< |
* ever contend so use simple builtin sync. |
1100 |
> |
* Returns the next sequence number. We don't expect this to |
1101 |
> |
* ever contend, so use simple builtin sync. |
1102 |
|
*/ |
1103 |
|
private static final synchronized int nextPoolId() { |
1104 |
|
return ++poolNumberSequence; |
1122 |
|
private static final long FAST_IDLE_TIMEOUT = 200L * 1000L * 1000L; |
1123 |
|
|
1124 |
|
/** |
1125 |
+ |
* Tolerance for idle timeouts, to cope with timer undershoots |
1126 |
+ |
*/ |
1127 |
+ |
private static final long TIMEOUT_SLOP = 2000000L; |
1128 |
+ |
|
1129 |
+ |
/** |
1130 |
|
* The maximum stolen->joining link depth allowed in method |
1131 |
|
* tryHelpStealer. Must be a power of two. Depths for legitimate |
1132 |
|
* chains are unbounded, but we use a fixed constant to avoid |
1142 |
|
*/ |
1143 |
|
private static final int SEED_INCREMENT = 0x61c88647; |
1144 |
|
|
1145 |
< |
/** |
1145 |
> |
/* |
1146 |
|
* Bits and masks for control variables |
1147 |
|
* |
1148 |
|
* Field ctl is a long packed with: |
1226 |
|
static final int FIFO_QUEUE = 1; |
1227 |
|
static final int SHARED_QUEUE = -1; |
1228 |
|
|
1231 |
– |
// bounds for #steps in scan loop -- must be power 2 minus 1 |
1232 |
– |
private static final int MIN_SCAN = 0x1ff; // cover estimation slop |
1233 |
– |
private static final int MAX_SCAN = 0x1ffff; // 4 * max workers |
1234 |
– |
|
1235 |
– |
// Instance fields |
1236 |
– |
|
1237 |
– |
/* |
1238 |
– |
* Field layout of this class tends to matter more than one would |
1239 |
– |
* like. Runtime layout order is only loosely related to |
1240 |
– |
* declaration order and may differ across JVMs, but the following |
1241 |
– |
* empirically works OK on current JVMs. |
1242 |
– |
*/ |
1243 |
– |
|
1229 |
|
// Heuristic padding to ameliorate unfortunate memory placements |
1230 |
|
volatile long pad00, pad01, pad02, pad03, pad04, pad05, pad06; |
1231 |
|
|
1232 |
+ |
// Instance fields |
1233 |
|
volatile long stealCount; // collects worker counts |
1234 |
|
volatile long ctl; // main pool control |
1235 |
|
volatile int plock; // shutdown status and seqLock |
1236 |
|
volatile int indexSeed; // worker/submitter index seed |
1237 |
< |
final int config; // mode and parallelism level |
1237 |
> |
final short parallelism; // parallelism level |
1238 |
> |
final short mode; // LIFO/FIFO |
1239 |
|
WorkQueue[] workQueues; // main registry |
1240 |
|
final ForkJoinWorkerThreadFactory factory; |
1241 |
< |
final Thread.UncaughtExceptionHandler ueh; // per-worker UEH |
1241 |
> |
final UncaughtExceptionHandler ueh; // per-worker UEH |
1242 |
|
final String workerNamePrefix; // to create worker name string |
1243 |
|
|
1244 |
|
volatile Object pad10, pad11, pad12, pad13, pad14, pad15, pad16, pad17; |
1245 |
|
volatile Object pad18, pad19, pad1a, pad1b; |
1246 |
|
|
1247 |
< |
/* |
1247 |
> |
/** |
1248 |
|
* Acquires the plock lock to protect worker array and related |
1249 |
|
* updates. This method is called only if an initial CAS on plock |
1250 |
< |
* fails. This acts as a spinLock for normal cases, but falls back |
1250 |
> |
* fails. This acts as a spinlock for normal cases, but falls back |
1251 |
|
* to builtin monitor to block when (rarely) needed. This would be |
1252 |
|
* a terrible idea for a highly contended lock, but works fine as |
1253 |
< |
* a more conservative alternative to a pure spinlock. See |
1267 |
< |
* internal ConcurrentHashMap documentation for further |
1268 |
< |
* explanation of nearly the same construction. |
1253 |
> |
* a more conservative alternative to a pure spinlock. |
1254 |
|
*/ |
1255 |
|
private int acquirePlock() { |
1256 |
< |
int spins = PL_SPINS, r = 0, ps, nps; |
1256 |
> |
int spins = PL_SPINS, ps, nps; |
1257 |
|
for (;;) { |
1258 |
|
if (((ps = plock) & PL_LOCK) == 0 && |
1259 |
|
U.compareAndSwapInt(this, PLOCK, ps, nps = ps + PL_LOCK)) |
1260 |
|
return nps; |
1276 |
– |
else if (r == 0) { // randomize spins if possible |
1277 |
– |
Thread t = Thread.currentThread(); WorkQueue w; Submitter z; |
1278 |
– |
if ((t instanceof ForkJoinWorkerThread) && |
1279 |
– |
(w = ((ForkJoinWorkerThread)t).workQueue) != null) |
1280 |
– |
r = w.seed; |
1281 |
– |
else if ((z = submitters.get()) != null) |
1282 |
– |
r = z.seed; |
1283 |
– |
else |
1284 |
– |
r = 1; |
1285 |
– |
} |
1261 |
|
else if (spins >= 0) { |
1262 |
< |
r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift |
1288 |
< |
if (r >= 0) |
1262 |
> |
if (ThreadLocalRandom.current().nextInt() >= 0) |
1263 |
|
--spins; |
1264 |
|
} |
1265 |
|
else if (U.compareAndSwapInt(this, PLOCK, ps, ps | PL_SIGNAL)) { |
1291 |
|
} |
1292 |
|
|
1293 |
|
/** |
1294 |
< |
* Performs secondary initialization, called when plock is zero. |
1295 |
< |
* Creates workQueue array and sets plock to a valid value. The |
1322 |
< |
* lock body must be exception-free (so no try/finally) so we |
1323 |
< |
* optimistically allocate new array outside the lock and throw |
1324 |
< |
* away if (very rarely) not needed. (A similar tactic is used in |
1325 |
< |
* fullExternalPush.) Because the plock seq value can eventually |
1326 |
< |
* wrap around zero, this method harmlessly fails to reinitialize |
1327 |
< |
* if workQueues exists, while still advancing plock. |
1328 |
< |
* |
1329 |
< |
* Additionally tries to create the first worker. |
1330 |
< |
*/ |
1331 |
< |
private void initWorkers() { |
1332 |
< |
WorkQueue[] ws, nws; int ps; |
1333 |
< |
int p = config & SMASK; // find power of two table size |
1334 |
< |
int n = (p > 1) ? p - 1 : 1; // ensure at least 2 slots |
1335 |
< |
n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; |
1336 |
< |
n = (n + 1) << 1; |
1337 |
< |
if ((ws = workQueues) == null || ws.length == 0) |
1338 |
< |
nws = new WorkQueue[n]; |
1339 |
< |
else |
1340 |
< |
nws = null; |
1341 |
< |
if (((ps = plock) & PL_LOCK) != 0 || |
1342 |
< |
!U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK)) |
1343 |
< |
ps = acquirePlock(); |
1344 |
< |
if (((ws = workQueues) == null || ws.length == 0) && nws != null) |
1345 |
< |
workQueues = nws; |
1346 |
< |
int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN); |
1347 |
< |
if (!U.compareAndSwapInt(this, PLOCK, ps, nps)) |
1348 |
< |
releasePlock(nps); |
1349 |
< |
tryAddWorker(); |
1350 |
< |
} |
1351 |
< |
|
1352 |
< |
/** |
1353 |
< |
* Tries to create and start one worker. Adjusts counts etc on |
1354 |
< |
* failure. |
1294 |
> |
* Tries to create and start one worker if fewer than target |
1295 |
> |
* parallelism level exist. Adjusts counts etc on failure. |
1296 |
|
*/ |
1297 |
|
private void tryAddWorker() { |
1298 |
< |
long c; int u; |
1298 |
> |
long c; int u, e; |
1299 |
|
while ((u = (int)((c = ctl) >>> 32)) < 0 && |
1300 |
< |
(u & SHORT_SIGN) != 0 && (int)c == 0) { |
1301 |
< |
long nc = (long)(((u + UTC_UNIT) & UTC_MASK) | |
1302 |
< |
((u + UAC_UNIT) & UAC_MASK)) << 32; |
1300 |
> |
(u & SHORT_SIGN) != 0 && (e = (int)c) >= 0) { |
1301 |
> |
long nc = ((long)(((u + UTC_UNIT) & UTC_MASK) | |
1302 |
> |
((u + UAC_UNIT) & UAC_MASK)) << 32) | (long)e; |
1303 |
|
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
1304 |
|
ForkJoinWorkerThreadFactory fac; |
1305 |
|
Throwable ex = null; |
1310 |
|
wt.start(); |
1311 |
|
break; |
1312 |
|
} |
1313 |
< |
} catch (Throwable e) { |
1314 |
< |
ex = e; |
1313 |
> |
} catch (Throwable rex) { |
1314 |
> |
ex = rex; |
1315 |
|
} |
1316 |
|
deregisterWorker(wt, ex); |
1317 |
|
break; |
1332 |
|
* @return the worker's queue |
1333 |
|
*/ |
1334 |
|
final WorkQueue registerWorker(ForkJoinWorkerThread wt) { |
1335 |
< |
Thread.UncaughtExceptionHandler handler; WorkQueue[] ws; int s, ps; |
1335 |
> |
UncaughtExceptionHandler handler; WorkQueue[] ws; int s, ps; |
1336 |
|
wt.setDaemon(true); |
1337 |
|
if ((handler = ueh) != null) |
1338 |
|
wt.setUncaughtExceptionHandler(handler); |
1339 |
|
do {} while (!U.compareAndSwapInt(this, INDEXSEED, s = indexSeed, |
1340 |
|
s += SEED_INCREMENT) || |
1341 |
|
s == 0); // skip 0 |
1342 |
< |
WorkQueue w = new WorkQueue(this, wt, config >>> 16, s); |
1342 |
> |
WorkQueue w = new WorkQueue(this, wt, mode, s); |
1343 |
|
if (((ps = plock) & PL_LOCK) != 0 || |
1344 |
|
!U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK)) |
1345 |
|
ps = acquirePlock(); |
1359 |
|
} |
1360 |
|
} |
1361 |
|
} |
1362 |
< |
w.eventCount = w.poolIndex = r; // volatile write orders |
1362 |
> |
w.poolIndex = (short)r; |
1363 |
> |
w.eventCount = r; // volatile write orders |
1364 |
|
ws[r] = w; |
1365 |
|
} |
1366 |
|
} finally { |
1367 |
|
if (!U.compareAndSwapInt(this, PLOCK, ps, nps)) |
1368 |
|
releasePlock(nps); |
1369 |
|
} |
1370 |
< |
wt.setName(workerNamePrefix.concat(Integer.toString(w.poolIndex))); |
1370 |
> |
wt.setName(workerNamePrefix.concat(Integer.toString(w.poolIndex >>> 1))); |
1371 |
|
return w; |
1372 |
|
} |
1373 |
|
|
1377 |
|
* array, and adjusts counts. If pool is shutting down, tries to |
1378 |
|
* complete termination. |
1379 |
|
* |
1380 |
< |
* @param wt the worker thread or null if construction failed |
1380 |
> |
* @param wt the worker thread, or null if construction failed |
1381 |
|
* @param ex the exception causing failure, or null if none |
1382 |
|
*/ |
1383 |
|
final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) { |
1384 |
|
WorkQueue w = null; |
1385 |
|
if (wt != null && (w = wt.workQueue) != null) { |
1386 |
< |
int ps; |
1386 |
> |
int ps; long sc; |
1387 |
|
w.qlock = -1; // ensure set |
1446 |
– |
long ns = w.nsteals, sc; // collect steal count |
1388 |
|
do {} while (!U.compareAndSwapLong(this, STEALCOUNT, |
1389 |
< |
sc = stealCount, sc + ns)); |
1389 |
> |
sc = stealCount, |
1390 |
> |
sc + w.nsteals)); |
1391 |
|
if (((ps = plock) & PL_LOCK) != 0 || |
1392 |
|
!U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK)) |
1393 |
|
ps = acquirePlock(); |
1403 |
|
} |
1404 |
|
} |
1405 |
|
|
1406 |
< |
long c; // adjust ctl counts |
1406 |
> |
long c; // adjust ctl counts |
1407 |
|
do {} while (!U.compareAndSwapLong |
1408 |
|
(this, CTL, c = ctl, (((c - AC_UNIT) & AC_MASK) | |
1409 |
|
((c - TC_UNIT) & TC_MASK) | |
1410 |
|
(c & ~(AC_MASK|TC_MASK))))); |
1411 |
|
|
1412 |
< |
if (!tryTerminate(false, false) && w != null) { |
1413 |
< |
w.cancelAll(); // cancel remaining tasks |
1414 |
< |
if (w.array != null) // suppress signal if never ran |
1415 |
< |
tryAddWorker(); // create replacement |
1416 |
< |
if (ex == null) // help clean refs on way out |
1417 |
< |
ForkJoinTask.helpExpungeStaleExceptions(); |
1412 |
> |
if (!tryTerminate(false, false) && w != null && w.array != null) { |
1413 |
> |
w.cancelAll(); // cancel remaining tasks |
1414 |
> |
WorkQueue[] ws; WorkQueue v; Thread p; int u, i, e; |
1415 |
> |
while ((u = (int)((c = ctl) >>> 32)) < 0 && (e = (int)c) >= 0) { |
1416 |
> |
if (e > 0) { // activate or create replacement |
1417 |
> |
if ((ws = workQueues) == null || |
1418 |
> |
(i = e & SMASK) >= ws.length || |
1419 |
> |
(v = ws[i]) == null) |
1420 |
> |
break; |
1421 |
> |
long nc = (((long)(v.nextWait & E_MASK)) | |
1422 |
> |
((long)(u + UAC_UNIT) << 32)); |
1423 |
> |
if (v.eventCount != (e | INT_SIGN)) |
1424 |
> |
break; |
1425 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
1426 |
> |
v.eventCount = (e + E_SEQ) & E_MASK; |
1427 |
> |
if ((p = v.parker) != null) |
1428 |
> |
U.unpark(p); |
1429 |
> |
break; |
1430 |
> |
} |
1431 |
> |
} |
1432 |
> |
else { |
1433 |
> |
if ((short)u < 0) |
1434 |
> |
tryAddWorker(); |
1435 |
> |
break; |
1436 |
> |
} |
1437 |
> |
} |
1438 |
|
} |
1439 |
< |
|
1440 |
< |
if (ex != null) // rethrow |
1439 |
> |
if (ex == null) // help clean refs on way out |
1440 |
> |
ForkJoinTask.helpExpungeStaleExceptions(); |
1441 |
> |
else // rethrow |
1442 |
|
ForkJoinTask.rethrow(ex); |
1443 |
|
} |
1444 |
|
|
1445 |
|
// Submissions |
1446 |
|
|
1447 |
|
/** |
1448 |
+ |
* Per-thread records for threads that submit to pools. Currently |
1449 |
+ |
* holds only pseudo-random seed / index that is used to choose |
1450 |
+ |
* submission queues in method externalPush. In the future, this may |
1451 |
+ |
* also incorporate a means to implement different task rejection |
1452 |
+ |
* and resubmission policies. |
1453 |
+ |
* |
1454 |
+ |
* Seeds for submitters and workers/workQueues work in basically |
1455 |
+ |
* the same way but are initialized and updated using slightly |
1456 |
+ |
* different mechanics. Both are initialized using the same |
1457 |
+ |
* approach as in class ThreadLocal, where successive values are |
1458 |
+ |
* unlikely to collide with previous values. Seeds are then |
1459 |
+ |
* randomly modified upon collisions using xorshifts, which |
1460 |
+ |
* requires a non-zero seed. |
1461 |
+ |
*/ |
1462 |
+ |
static final class Submitter { |
1463 |
+ |
int seed; |
1464 |
+ |
Submitter(int s) { seed = s; } |
1465 |
+ |
} |
1466 |
+ |
|
1467 |
+ |
/** |
1468 |
|
* Unless shutting down, adds the given task to a submission queue |
1469 |
|
* at submitter's current queue index (modulo submission |
1470 |
|
* range). Only the most common path is directly handled in this |
1473 |
|
* @param task the task. Caller must ensure non-null. |
1474 |
|
*/ |
1475 |
|
final void externalPush(ForkJoinTask<?> task) { |
1476 |
< |
WorkQueue[] ws; WorkQueue q; Submitter z; int m; ForkJoinTask<?>[] a; |
1477 |
< |
if ((z = submitters.get()) != null && plock > 0 && |
1478 |
< |
(ws = workQueues) != null && (m = (ws.length - 1)) >= 0 && |
1479 |
< |
(q = ws[m & z.seed & SQMASK]) != null && |
1476 |
> |
Submitter z = submitters.get(); |
1477 |
> |
WorkQueue q; int r, m, s, n, am; ForkJoinTask<?>[] a; |
1478 |
> |
int ps = plock; |
1479 |
> |
WorkQueue[] ws = workQueues; |
1480 |
> |
if (z != null && ps > 0 && ws != null && (m = (ws.length - 1)) >= 0 && |
1481 |
> |
(q = ws[m & (r = z.seed) & SQMASK]) != null && r != 0 && |
1482 |
|
U.compareAndSwapInt(q, QLOCK, 0, 1)) { // lock |
1483 |
< |
int b = q.base, s = q.top, n, an; |
1484 |
< |
if ((a = q.array) != null && (an = a.length) > (n = s + 1 - b)) { |
1485 |
< |
int j = (((an - 1) & s) << ASHIFT) + ABASE; |
1483 |
> |
if ((a = q.array) != null && |
1484 |
> |
(am = a.length - 1) > (n = (s = q.top) - q.base)) { |
1485 |
> |
int j = ((am & s) << ASHIFT) + ABASE; |
1486 |
|
U.putOrderedObject(a, j, task); |
1487 |
|
q.top = s + 1; // push on to deque |
1488 |
|
q.qlock = 0; |
1489 |
< |
if (n <= 2) |
1490 |
< |
signalWork(q); |
1489 |
> |
if (n <= 1) |
1490 |
> |
signalWork(ws, q); |
1491 |
|
return; |
1492 |
|
} |
1493 |
|
q.qlock = 0; |
1498 |
|
/** |
1499 |
|
* Full version of externalPush. This method is called, among |
1500 |
|
* other times, upon the first submission of the first task to the |
1501 |
< |
* pool, so must perform secondary initialization (via |
1502 |
< |
* initWorkers). It also detects first submission by an external |
1503 |
< |
* thread by looking up its ThreadLocal, and creates a new shared |
1504 |
< |
* queue if the one at index if empty or contended. The plock lock |
1505 |
< |
* body must be exception-free (so no try/finally) so we |
1506 |
< |
* optimistically allocate new queues outside the lock and throw |
1507 |
< |
* them away if (very rarely) not needed. |
1501 |
> |
* pool, so must perform secondary initialization. It also |
1502 |
> |
* detects first submission by an external thread by looking up |
1503 |
> |
* its ThreadLocal, and creates a new shared queue if the one at |
1504 |
> |
* index if empty or contended. The plock lock body must be |
1505 |
> |
* exception-free (so no try/finally) so we optimistically |
1506 |
> |
* allocate new queues outside the lock and throw them away if |
1507 |
> |
* (very rarely) not needed. |
1508 |
> |
* |
1509 |
> |
* Secondary initialization occurs when plock is zero, to create |
1510 |
> |
* workQueue array and set plock to a valid value. This lock body |
1511 |
> |
* must also be exception-free. Because the plock seq value can |
1512 |
> |
* eventually wrap around zero, this method harmlessly fails to |
1513 |
> |
* reinitialize if workQueues exists, while still advancing plock. |
1514 |
|
*/ |
1515 |
|
private void fullExternalPush(ForkJoinTask<?> task) { |
1516 |
|
int r = 0; // random index seed |
1521 |
|
r += SEED_INCREMENT) && r != 0) |
1522 |
|
submitters.set(z = new Submitter(r)); |
1523 |
|
} |
1524 |
< |
else if (r == 0) { // move to a different index |
1524 |
> |
else if (r == 0) { // move to a different index |
1525 |
|
r = z.seed; |
1526 |
< |
r ^= r << 13; // same xorshift as WorkQueues |
1526 |
> |
r ^= r << 13; // same xorshift as WorkQueues |
1527 |
|
r ^= r >>> 17; |
1528 |
< |
z.seed = r ^ (r << 5); |
1528 |
> |
z.seed = r ^= (r << 5); |
1529 |
|
} |
1530 |
< |
else if ((ps = plock) < 0) |
1530 |
> |
if ((ps = plock) < 0) |
1531 |
|
throw new RejectedExecutionException(); |
1532 |
|
else if (ps == 0 || (ws = workQueues) == null || |
1533 |
< |
(m = ws.length - 1) < 0) |
1534 |
< |
initWorkers(); |
1533 |
> |
(m = ws.length - 1) < 0) { // initialize workQueues |
1534 |
> |
int p = parallelism; // find power of two table size |
1535 |
> |
int n = (p > 1) ? p - 1 : 1; // ensure at least 2 slots |
1536 |
> |
n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; |
1537 |
> |
n |= n >>> 8; n |= n >>> 16; n = (n + 1) << 1; |
1538 |
> |
WorkQueue[] nws = ((ws = workQueues) == null || ws.length == 0 ? |
1539 |
> |
new WorkQueue[n] : null); |
1540 |
> |
if (((ps = plock) & PL_LOCK) != 0 || |
1541 |
> |
!U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK)) |
1542 |
> |
ps = acquirePlock(); |
1543 |
> |
if (((ws = workQueues) == null || ws.length == 0) && nws != null) |
1544 |
> |
workQueues = nws; |
1545 |
> |
int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN); |
1546 |
> |
if (!U.compareAndSwapInt(this, PLOCK, ps, nps)) |
1547 |
> |
releasePlock(nps); |
1548 |
> |
} |
1549 |
|
else if ((q = ws[k = r & m & SQMASK]) != null) { |
1550 |
|
if (q.qlock == 0 && U.compareAndSwapInt(q, QLOCK, 0, 1)) { |
1551 |
|
ForkJoinTask<?>[] a = q.array; |
1563 |
|
q.qlock = 0; // unlock |
1564 |
|
} |
1565 |
|
if (submitted) { |
1566 |
< |
signalWork(q); |
1566 |
> |
signalWork(ws, q); |
1567 |
|
return; |
1568 |
|
} |
1569 |
|
} |
1571 |
|
} |
1572 |
|
else if (((ps = plock) & PL_LOCK) == 0) { // create new queue |
1573 |
|
q = new WorkQueue(this, null, SHARED_QUEUE, r); |
1574 |
+ |
q.poolIndex = (short)k; |
1575 |
|
if (((ps = plock) & PL_LOCK) != 0 || |
1576 |
|
!U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK)) |
1577 |
|
ps = acquirePlock(); |
1582 |
|
releasePlock(nps); |
1583 |
|
} |
1584 |
|
else |
1585 |
< |
r = 0; // try elsewhere while lock held |
1585 |
> |
r = 0; |
1586 |
|
} |
1587 |
|
} |
1588 |
|
|
1593 |
|
*/ |
1594 |
|
final void incrementActiveCount() { |
1595 |
|
long c; |
1596 |
< |
do {} while (!U.compareAndSwapLong(this, CTL, c = ctl, c + AC_UNIT)); |
1596 |
> |
do {} while (!U.compareAndSwapLong |
1597 |
> |
(this, CTL, c = ctl, ((c & ~AC_MASK) | |
1598 |
> |
((c & AC_MASK) + AC_UNIT)))); |
1599 |
|
} |
1600 |
|
|
1601 |
|
/** |
1602 |
|
* Tries to create or activate a worker if too few are active. |
1603 |
|
* |
1604 |
< |
* @param q the (non-null) queue holding tasks to be signalled |
1604 |
> |
* @param ws the worker array to use to find signallees |
1605 |
> |
* @param q if non-null, the queue holding tasks to be processed |
1606 |
|
*/ |
1607 |
< |
final void signalWork(WorkQueue q) { |
1608 |
< |
int hint = q.poolIndex; |
1609 |
< |
long c; int e, u, i, n; WorkQueue[] ws; WorkQueue w; Thread p; |
1610 |
< |
while ((u = (int)((c = ctl) >>> 32)) < 0) { |
1611 |
< |
if ((e = (int)c) > 0) { |
1612 |
< |
if ((ws = workQueues) != null && ws.length > (i = e & SMASK) && |
1604 |
< |
(w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) { |
1605 |
< |
long nc = (((long)(w.nextWait & E_MASK)) | |
1606 |
< |
((long)(u + UAC_UNIT) << 32)); |
1607 |
< |
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
1608 |
< |
w.hint = hint; |
1609 |
< |
w.eventCount = (e + E_SEQ) & E_MASK; |
1610 |
< |
if ((p = w.parker) != null) |
1611 |
< |
U.unpark(p); |
1612 |
< |
break; |
1613 |
< |
} |
1614 |
< |
if (q.top - q.base <= 0) |
1615 |
< |
break; |
1616 |
< |
} |
1617 |
< |
else |
1618 |
< |
break; |
1619 |
< |
} |
1620 |
< |
else { |
1607 |
> |
final void signalWork(WorkQueue[] ws, WorkQueue q) { |
1608 |
> |
for (;;) { |
1609 |
> |
long c; int e, u, i; WorkQueue w; Thread p; |
1610 |
> |
if ((u = (int)((c = ctl) >>> 32)) >= 0) |
1611 |
> |
break; |
1612 |
> |
if ((e = (int)c) <= 0) { |
1613 |
|
if ((short)u < 0) |
1614 |
|
tryAddWorker(); |
1615 |
|
break; |
1616 |
|
} |
1617 |
+ |
if (ws == null || ws.length <= (i = e & SMASK) || |
1618 |
+ |
(w = ws[i]) == null) |
1619 |
+ |
break; |
1620 |
+ |
long nc = (((long)(w.nextWait & E_MASK)) | |
1621 |
+ |
((long)(u + UAC_UNIT)) << 32); |
1622 |
+ |
int ne = (e + E_SEQ) & E_MASK; |
1623 |
+ |
if (w.eventCount == (e | INT_SIGN) && |
1624 |
+ |
U.compareAndSwapLong(this, CTL, c, nc)) { |
1625 |
+ |
w.eventCount = ne; |
1626 |
+ |
if ((p = w.parker) != null) |
1627 |
+ |
U.unpark(p); |
1628 |
+ |
break; |
1629 |
+ |
} |
1630 |
+ |
if (q != null && q.base >= q.top) |
1631 |
+ |
break; |
1632 |
|
} |
1633 |
|
} |
1634 |
|
|
1639 |
|
*/ |
1640 |
|
final void runWorker(WorkQueue w) { |
1641 |
|
w.growArray(); // allocate queue |
1642 |
< |
do { w.runTask(scan(w)); } while (w.qlock >= 0); |
1642 |
> |
for (int r = w.hint; scan(w, r) == 0; ) { |
1643 |
> |
r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift |
1644 |
> |
} |
1645 |
|
} |
1646 |
|
|
1647 |
|
/** |
1648 |
< |
* Scans for and, if found, returns one task, else possibly |
1648 |
> |
* Scans for and, if found, runs one task, else possibly |
1649 |
|
* inactivates the worker. This method operates on single reads of |
1650 |
|
* volatile state and is designed to be re-invoked continuously, |
1651 |
|
* in part because it returns upon detecting inconsistencies, |
1652 |
|
* contention, or state changes that indicate possible success on |
1653 |
|
* re-invocation. |
1654 |
|
* |
1655 |
< |
* The scan searches for tasks across queues (starting at a random |
1656 |
< |
* index, and relying on registerWorker to irregularly scatter |
1657 |
< |
* them within array to avoid bias), checking each at least twice. |
1658 |
< |
* The scan terminates upon either finding a non-empty queue, or |
1659 |
< |
* completing the sweep. If the worker is not inactivated, it |
1660 |
< |
* takes and returns a task from this queue. Otherwise, if not |
1661 |
< |
* activated, it signals workers (that may include itself) and |
1662 |
< |
* returns so caller can retry. Also returns for true if the |
1663 |
< |
* worker array may have changed during an empty scan. On failure |
1655 |
< |
* to find a task, we take one of the following actions, after |
1656 |
< |
* which the caller will retry calling this method unless |
1657 |
< |
* terminated. |
1658 |
< |
* |
1659 |
< |
* * If pool is terminating, terminate the worker. |
1660 |
< |
* |
1661 |
< |
* * If not already enqueued, try to inactivate and enqueue the |
1662 |
< |
* worker on wait queue. Or, if inactivating has caused the pool |
1663 |
< |
* to be quiescent, relay to idleAwaitWork to check for |
1664 |
< |
* termination and possibly shrink pool. |
1665 |
< |
* |
1666 |
< |
* * If already enqueued and none of the above apply, possibly |
1667 |
< |
* (with 1/2 probability) park awaiting signal, else lingering to |
1668 |
< |
* help scan and signal. |
1655 |
> |
* The scan searches for tasks across queues starting at a random |
1656 |
> |
* index, checking each at least twice. The scan terminates upon |
1657 |
> |
* either finding a non-empty queue, or completing the sweep. If |
1658 |
> |
* the worker is not inactivated, it takes and runs a task from |
1659 |
> |
* this queue. Otherwise, if not activated, it tries to activate |
1660 |
> |
* itself or some other worker by signalling. On failure to find a |
1661 |
> |
* task, returns (for retry) if pool state may have changed during |
1662 |
> |
* an empty scan, or tries to inactivate if active, else possibly |
1663 |
> |
* blocks or terminates via method awaitWork. |
1664 |
|
* |
1665 |
|
* @param w the worker (via its WorkQueue) |
1666 |
< |
* @return a task or null if none found |
1666 |
> |
* @param r a random seed |
1667 |
> |
* @return worker qlock status if would have waited, else 0 |
1668 |
|
*/ |
1669 |
< |
private final ForkJoinTask<?> scan(WorkQueue w) { |
1669 |
> |
private final int scan(WorkQueue w, int r) { |
1670 |
|
WorkQueue[] ws; int m; |
1671 |
< |
int ps = plock; // read plock before ws |
1672 |
< |
if (w != null && (ws = workQueues) != null && (m = ws.length - 1) >= 0) { |
1673 |
< |
int ec = w.eventCount; // ec is negative if inactive |
1674 |
< |
int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5; |
1675 |
< |
int j = ((m + m + 1) | MIN_SCAN) & MAX_SCAN; |
1676 |
< |
do { |
1677 |
< |
WorkQueue q; ForkJoinTask<?>[] a; int b; |
1678 |
< |
if ((q = ws[(r + j) & m]) != null && (b = q.base) - q.top < 0 && |
1679 |
< |
(a = q.array) != null) { // probably nonempty |
1680 |
< |
int i = (((a.length - 1) & b) << ASHIFT) + ABASE; |
1681 |
< |
ForkJoinTask<?> t = (ForkJoinTask<?>) |
1682 |
< |
U.getObjectVolatile(a, i); |
1683 |
< |
if (q.base == b && ec >= 0 && t != null && |
1684 |
< |
U.compareAndSwapObject(a, i, t, null)) { |
1685 |
< |
if ((q.base = b + 1) - q.top < 0) |
1686 |
< |
signalWork(q); |
1687 |
< |
return t; // taken |
1688 |
< |
} |
1689 |
< |
else if ((ec < 0 || j < m) && (int)(ctl >> AC_SHIFT) <= 0) { |
1690 |
< |
w.hint = (r + j) & m; // help signal below |
1695 |
< |
break; // cannot take |
1696 |
< |
} |
1697 |
< |
} |
1698 |
< |
} while (--j >= 0); |
1699 |
< |
|
1700 |
< |
long c, sc; int e, ns, h; |
1701 |
< |
if ((h = w.hint) < 0) { |
1702 |
< |
if ((ns = w.nsteals) != 0) { |
1703 |
< |
if (U.compareAndSwapLong(this, STEALCOUNT, |
1704 |
< |
sc = stealCount, sc + ns)) |
1705 |
< |
w.nsteals = 0; // collect steals |
1706 |
< |
} |
1707 |
< |
else if (plock != ps) // consistency check |
1708 |
< |
; // skip |
1709 |
< |
else if ((e = (int)(c = ctl)) < 0) |
1710 |
< |
w.qlock = -1; // pool is terminating |
1711 |
< |
else if (ec >= 0) { // try to enqueue/inactivate |
1712 |
< |
long nc = ((long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK))); |
1713 |
< |
w.nextWait = e; // link and mark inactive |
1714 |
< |
w.eventCount = ec | INT_SIGN; |
1715 |
< |
if (ctl != c || !U.compareAndSwapLong(this, CTL, c, nc)) |
1716 |
< |
w.eventCount = ec; // unmark on CAS failure |
1717 |
< |
else if ((int)(c >> AC_SHIFT) == 1 - (config & SMASK)) |
1718 |
< |
idleAwaitWork(w, nc, c); |
1671 |
> |
long c = ctl; // for consistency check |
1672 |
> |
if ((ws = workQueues) != null && (m = ws.length - 1) >= 0 && w != null) { |
1673 |
> |
for (int j = m + m + 1, ec = w.eventCount;;) { |
1674 |
> |
WorkQueue q; int b, e; ForkJoinTask<?>[] a; ForkJoinTask<?> t; |
1675 |
> |
if ((q = ws[(r - j) & m]) != null && |
1676 |
> |
(b = q.base) - q.top < 0 && (a = q.array) != null) { |
1677 |
> |
long i = (((a.length - 1) & b) << ASHIFT) + ABASE; |
1678 |
> |
if ((t = ((ForkJoinTask<?>) |
1679 |
> |
U.getObjectVolatile(a, i))) != null) { |
1680 |
> |
if (ec < 0) |
1681 |
> |
helpRelease(c, ws, w, q, b); |
1682 |
> |
else if (q.base == b && |
1683 |
> |
U.compareAndSwapObject(a, i, t, null)) { |
1684 |
> |
U.putOrderedInt(q, QBASE, b + 1); |
1685 |
> |
if ((b + 1) - q.top < 0) |
1686 |
> |
signalWork(ws, q); |
1687 |
> |
w.runTask(t); |
1688 |
> |
} |
1689 |
> |
} |
1690 |
> |
break; |
1691 |
|
} |
1692 |
< |
else if (w.eventCount < 0) { // block |
1693 |
< |
Thread wt = Thread.currentThread(); |
1694 |
< |
Thread.interrupted(); // clear status |
1695 |
< |
U.putObject(wt, PARKBLOCKER, this); |
1696 |
< |
w.parker = wt; // emulate LockSupport.park |
1697 |
< |
if (w.eventCount < 0) // recheck |
1698 |
< |
U.park(false, 0L); |
1699 |
< |
w.parker = null; |
1700 |
< |
U.putObject(wt, PARKBLOCKER, null); |
1692 |
> |
else if (--j < 0) { |
1693 |
> |
if ((ec | (e = (int)c)) < 0) // inactive or terminating |
1694 |
> |
return awaitWork(w, c, ec); |
1695 |
> |
else if (ctl == c) { // try to inactivate and enqueue |
1696 |
> |
long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK)); |
1697 |
> |
w.nextWait = e; |
1698 |
> |
w.eventCount = ec | INT_SIGN; |
1699 |
> |
if (!U.compareAndSwapLong(this, CTL, c, nc)) |
1700 |
> |
w.eventCount = ec; // back out |
1701 |
> |
} |
1702 |
> |
break; |
1703 |
|
} |
1704 |
|
} |
1731 |
– |
if (h >= 0 || (h = w.hint) >= 0) { // signal others before retry |
1732 |
– |
w.hint = -1; // reset |
1733 |
– |
helpSignal(null, h, true); |
1734 |
– |
} |
1705 |
|
} |
1706 |
< |
return null; |
1706 |
> |
return 0; |
1707 |
|
} |
1708 |
|
|
1709 |
|
/** |
1710 |
< |
* If inactivating worker w has caused the pool to become |
1711 |
< |
* quiescent, checks for pool termination, and, so long as this is |
1712 |
< |
* not the only worker, waits for event for up to a given |
1713 |
< |
* duration. On timeout, if ctl has not changed, terminates the |
1714 |
< |
* worker, which will in turn wake up another worker to possibly |
1715 |
< |
* repeat this process. |
1710 |
> |
* A continuation of scan(), possibly blocking or terminating |
1711 |
> |
* worker w. Returns without blocking if pool state has apparently |
1712 |
> |
* changed since last invocation. Also, if inactivating w has |
1713 |
> |
* caused the pool to become quiescent, checks for pool |
1714 |
> |
* termination, and, so long as this is not the only worker, waits |
1715 |
> |
* for event for up to a given duration. On timeout, if ctl has |
1716 |
> |
* not changed, terminates the worker, which will in turn wake up |
1717 |
> |
* another worker to possibly repeat this process. |
1718 |
|
* |
1719 |
|
* @param w the calling worker |
1720 |
< |
* @param currentCtl the ctl value triggering possible quiescence |
1721 |
< |
* @param prevCtl the ctl value to restore if thread is terminated |
1720 |
> |
* @param c the ctl value on entry to scan |
1721 |
> |
* @param ec the worker's eventCount on entry to scan |
1722 |
|
*/ |
1723 |
< |
private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) { |
1724 |
< |
if (w != null && w.eventCount < 0 && |
1725 |
< |
!tryTerminate(false, false) && (int)prevCtl != 0) { |
1726 |
< |
int dc = -(short)(currentCtl >>> TC_SHIFT); |
1727 |
< |
long parkTime = dc < 0 ? FAST_IDLE_TIMEOUT: (dc + 1) * IDLE_TIMEOUT; |
1728 |
< |
long deadline = System.nanoTime() + parkTime - 100000L; // 1ms slop |
1729 |
< |
Thread wt = Thread.currentThread(); |
1730 |
< |
while (ctl == currentCtl) { |
1731 |
< |
Thread.interrupted(); // timed variant of version in scan() |
1732 |
< |
U.putObject(wt, PARKBLOCKER, this); |
1733 |
< |
w.parker = wt; |
1734 |
< |
if (ctl == currentCtl) |
1735 |
< |
U.park(false, parkTime); |
1736 |
< |
w.parker = null; |
1737 |
< |
U.putObject(wt, PARKBLOCKER, null); |
1738 |
< |
if (ctl != currentCtl) |
1739 |
< |
break; |
1740 |
< |
if (deadline - System.nanoTime() <= 0L && |
1741 |
< |
U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) { |
1742 |
< |
w.eventCount = (w.eventCount + E_SEQ) | E_MASK; |
1743 |
< |
w.qlock = -1; // shrink |
1744 |
< |
break; |
1723 |
> |
private final int awaitWork(WorkQueue w, long c, int ec) { |
1724 |
> |
int stat, ns; long parkTime, deadline; |
1725 |
> |
if ((stat = w.qlock) >= 0 && w.eventCount == ec && ctl == c && |
1726 |
> |
!Thread.interrupted()) { |
1727 |
> |
int e = (int)c; |
1728 |
> |
int u = (int)(c >>> 32); |
1729 |
> |
int d = (u >> UAC_SHIFT) + parallelism; // active count |
1730 |
> |
|
1731 |
> |
if (e < 0 || (d <= 0 && tryTerminate(false, false))) |
1732 |
> |
stat = w.qlock = -1; // pool is terminating |
1733 |
> |
else if ((ns = w.nsteals) != 0) { // collect steals and retry |
1734 |
> |
long sc; |
1735 |
> |
w.nsteals = 0; |
1736 |
> |
do {} while (!U.compareAndSwapLong(this, STEALCOUNT, |
1737 |
> |
sc = stealCount, sc + ns)); |
1738 |
> |
} |
1739 |
> |
else { |
1740 |
> |
long pc = ((d > 0 || ec != (e | INT_SIGN)) ? 0L : |
1741 |
> |
((long)(w.nextWait & E_MASK)) | // ctl to restore |
1742 |
> |
((long)(u + UAC_UNIT)) << 32); |
1743 |
> |
if (pc != 0L) { // timed wait if last waiter |
1744 |
> |
int dc = -(short)(c >>> TC_SHIFT); |
1745 |
> |
parkTime = (dc < 0 ? FAST_IDLE_TIMEOUT: |
1746 |
> |
(dc + 1) * IDLE_TIMEOUT); |
1747 |
> |
deadline = System.nanoTime() + parkTime - TIMEOUT_SLOP; |
1748 |
> |
} |
1749 |
> |
else |
1750 |
> |
parkTime = deadline = 0L; |
1751 |
> |
if (w.eventCount == ec && ctl == c) { |
1752 |
> |
Thread wt = Thread.currentThread(); |
1753 |
> |
U.putObject(wt, PARKBLOCKER, this); |
1754 |
> |
w.parker = wt; // emulate LockSupport.park |
1755 |
> |
if (w.eventCount == ec && ctl == c) |
1756 |
> |
U.park(false, parkTime); // must recheck before park |
1757 |
> |
w.parker = null; |
1758 |
> |
U.putObject(wt, PARKBLOCKER, null); |
1759 |
> |
if (parkTime != 0L && ctl == c && |
1760 |
> |
deadline - System.nanoTime() <= 0L && |
1761 |
> |
U.compareAndSwapLong(this, CTL, c, pc)) |
1762 |
> |
stat = w.qlock = -1; // shrink pool |
1763 |
|
} |
1764 |
|
} |
1765 |
|
} |
1766 |
+ |
return stat; |
1767 |
|
} |
1768 |
|
|
1769 |
|
/** |
1770 |
< |
* Scans through queues looking for work (optionally, while |
1771 |
< |
* joining a task); if any present, signals. May return early if |
1772 |
< |
* more signalling is detectably unneeded. |
1773 |
< |
* |
1774 |
< |
* @param task if non-null, return early if done |
1775 |
< |
* @param origin an index to start scan |
1776 |
< |
* @param once if only the origin should be checked |
1777 |
< |
*/ |
1778 |
< |
private void helpSignal(ForkJoinTask<?> task, int origin, boolean once) { |
1779 |
< |
WorkQueue[] ws; WorkQueue w; Thread p; long c; int m, u, e, i, s; |
1780 |
< |
if ((u = (int)(ctl >>> 32)) < 0 && (u >> UAC_SHIFT) < 0 && |
1781 |
< |
(ws = workQueues) != null && (m = ws.length - 1) >= 0) { |
1782 |
< |
outer: for (int k = origin, j = once ? 0 : m; j >= 0; --j) { |
1783 |
< |
WorkQueue q = ws[k++ & m]; |
1784 |
< |
for (int n = m;;) { // limit to at most m signals |
1785 |
< |
if (task != null && task.status < 0) |
1786 |
< |
break outer; |
1787 |
< |
if (q == null || |
1788 |
< |
((s = (task == null ? -1 : 0) - q.base + q.top) <= n && |
1789 |
< |
(n = s) <= 0)) |
1799 |
< |
break; |
1800 |
< |
if ((u = (int)((c = ctl) >>> 32)) >= 0 || |
1801 |
< |
(e = (int)c) <= 0 || m < (i = e & SMASK) || |
1802 |
< |
(w = ws[i]) == null) |
1803 |
< |
break outer; |
1804 |
< |
long nc = (((long)(w.nextWait & E_MASK)) | |
1805 |
< |
((long)(u + UAC_UNIT) << 32)); |
1806 |
< |
if (w.eventCount == (e | INT_SIGN) && |
1807 |
< |
U.compareAndSwapLong(this, CTL, c, nc)) { |
1808 |
< |
w.eventCount = (e + E_SEQ) & E_MASK; |
1809 |
< |
if ((p = w.parker) != null) |
1810 |
< |
U.unpark(p); |
1811 |
< |
if (--n <= 0) |
1812 |
< |
break; |
1813 |
< |
} |
1814 |
< |
} |
1770 |
> |
* Possibly releases (signals) a worker. Called only from scan() |
1771 |
> |
* when a worker with apparently inactive status finds a non-empty |
1772 |
> |
* queue. This requires revalidating all of the associated state |
1773 |
> |
* from caller. |
1774 |
> |
*/ |
1775 |
> |
private final void helpRelease(long c, WorkQueue[] ws, WorkQueue w, |
1776 |
> |
WorkQueue q, int b) { |
1777 |
> |
WorkQueue v; int e, i; Thread p; |
1778 |
> |
if (w != null && w.eventCount < 0 && (e = (int)c) > 0 && |
1779 |
> |
ws != null && ws.length > (i = e & SMASK) && |
1780 |
> |
(v = ws[i]) != null && ctl == c) { |
1781 |
> |
long nc = (((long)(v.nextWait & E_MASK)) | |
1782 |
> |
((long)((int)(c >>> 32) + UAC_UNIT)) << 32); |
1783 |
> |
int ne = (e + E_SEQ) & E_MASK; |
1784 |
> |
if (q != null && q.base == b && w.eventCount < 0 && |
1785 |
> |
v.eventCount == (e | INT_SIGN) && |
1786 |
> |
U.compareAndSwapLong(this, CTL, c, nc)) { |
1787 |
> |
v.eventCount = ne; |
1788 |
> |
if ((p = v.parker) != null) |
1789 |
> |
U.unpark(p); |
1790 |
|
} |
1791 |
|
} |
1792 |
|
} |
1811 |
|
*/ |
1812 |
|
private int tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) { |
1813 |
|
int stat = 0, steps = 0; // bound to avoid cycles |
1814 |
< |
if (joiner != null && task != null) { // hoist null checks |
1814 |
> |
if (task != null && joiner != null && |
1815 |
> |
joiner.base - joiner.top >= 0) { // hoist checks |
1816 |
|
restart: for (;;) { |
1817 |
|
ForkJoinTask<?> subtask = task; // current target |
1818 |
|
for (WorkQueue j = joiner, v;;) { // v is stealer of subtask |
1839 |
|
} |
1840 |
|
} |
1841 |
|
for (;;) { // help stealer or descend to its stealer |
1842 |
< |
ForkJoinTask[] a; int b; |
1842 |
> |
ForkJoinTask[] a; int b; |
1843 |
|
if (subtask.status < 0) // surround probes with |
1844 |
|
continue restart; // consistency checks |
1845 |
|
if ((b = v.base) - v.top < 0 && (a = v.array) != null) { |
1850 |
|
v.currentSteal != subtask) |
1851 |
|
continue restart; // stale |
1852 |
|
stat = 1; // apparent progress |
1853 |
< |
if (t != null && v.base == b && |
1854 |
< |
U.compareAndSwapObject(a, i, t, null)) { |
1855 |
< |
v.base = b + 1; // help stealer |
1856 |
< |
joiner.runSubtask(t); |
1853 |
> |
if (v.base == b) { |
1854 |
> |
if (t == null) |
1855 |
> |
break restart; |
1856 |
> |
if (U.compareAndSwapObject(a, i, t, null)) { |
1857 |
> |
U.putOrderedInt(v, QBASE, b + 1); |
1858 |
> |
ForkJoinTask<?> ps = joiner.currentSteal; |
1859 |
> |
int jt = joiner.top; |
1860 |
> |
do { |
1861 |
> |
joiner.currentSteal = t; |
1862 |
> |
t.doExec(); // clear local tasks too |
1863 |
> |
} while (task.status >= 0 && |
1864 |
> |
joiner.top != jt && |
1865 |
> |
(t = joiner.pop()) != null); |
1866 |
> |
joiner.currentSteal = ps; |
1867 |
> |
break restart; |
1868 |
> |
} |
1869 |
|
} |
1882 |
– |
else if (v.base == b && ++steps == MAX_HELP) |
1883 |
– |
break restart; // v apparently stalled |
1870 |
|
} |
1871 |
|
else { // empty -- try to descend |
1872 |
|
ForkJoinTask<?> next = v.currentJoin; |
1893 |
|
* and run tasks within the target's computation. |
1894 |
|
* |
1895 |
|
* @param task the task to join |
1910 |
– |
* @param mode if shared, exit upon completing any task |
1911 |
– |
* if all workers are active |
1912 |
– |
* |
1896 |
|
*/ |
1897 |
< |
private int helpComplete(ForkJoinTask<?> task, int mode) { |
1898 |
< |
WorkQueue[] ws; WorkQueue q; int m, n, s, u; |
1899 |
< |
if (task != null && (ws = workQueues) != null && |
1900 |
< |
(m = ws.length - 1) >= 0) { |
1901 |
< |
for (int j = 1, origin = j;;) { |
1897 |
> |
private int helpComplete(WorkQueue joiner, CountedCompleter<?> task) { |
1898 |
> |
WorkQueue[] ws; int m; |
1899 |
> |
int s = 0; |
1900 |
> |
if ((ws = workQueues) != null && (m = ws.length - 1) >= 0 && |
1901 |
> |
joiner != null && task != null) { |
1902 |
> |
int j = joiner.poolIndex; |
1903 |
> |
int scans = m + m + 1; |
1904 |
> |
long c = 0L; // for stability check |
1905 |
> |
for (int k = scans; ; j += 2) { |
1906 |
> |
WorkQueue q; |
1907 |
|
if ((s = task.status) < 0) |
1908 |
< |
return s; |
1909 |
< |
if ((q = ws[j & m]) != null && q.pollAndExecCC(task)) { |
1910 |
< |
origin = j; |
1911 |
< |
if (mode == SHARED_QUEUE && |
1912 |
< |
((u = (int)(ctl >>> 32)) >= 0 || (u >> UAC_SHIFT) >= 0)) |
1908 |
> |
break; |
1909 |
> |
else if (joiner.internalPopAndExecCC(task)) |
1910 |
> |
k = scans; |
1911 |
> |
else if ((s = task.status) < 0) |
1912 |
> |
break; |
1913 |
> |
else if ((q = ws[j & m]) != null && q.pollAndExecCC(task)) |
1914 |
> |
k = scans; |
1915 |
> |
else if (--k < 0) { |
1916 |
> |
if (c == (c = ctl)) |
1917 |
|
break; |
1918 |
+ |
k = scans; |
1919 |
|
} |
1927 |
– |
else if ((j = (j + 2) & m) == origin) |
1928 |
– |
break; |
1920 |
|
} |
1921 |
|
} |
1922 |
< |
return 0; |
1922 |
> |
return s; |
1923 |
|
} |
1924 |
|
|
1925 |
|
/** |
1928 |
|
* for blocking. Fails on contention or termination. Otherwise, |
1929 |
|
* adds a new thread if no idle workers are available and pool |
1930 |
|
* may become starved. |
1931 |
+ |
* |
1932 |
+ |
* @param c the assumed ctl value |
1933 |
|
*/ |
1934 |
< |
final boolean tryCompensate() { |
1935 |
< |
int pc = config & SMASK, e, i, tc; long c; |
1936 |
< |
WorkQueue[] ws; WorkQueue w; Thread p; |
1937 |
< |
if ((ws = workQueues) != null && (e = (int)(c = ctl)) >= 0) { |
1938 |
< |
if (e != 0 && (i = e & SMASK) < ws.length && |
1939 |
< |
(w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) { |
1934 |
> |
final boolean tryCompensate(long c) { |
1935 |
> |
WorkQueue[] ws = workQueues; |
1936 |
> |
int pc = parallelism, e = (int)c, m, tc; |
1937 |
> |
if (ws != null && (m = ws.length - 1) >= 0 && e >= 0 && ctl == c) { |
1938 |
> |
WorkQueue w = ws[e & m]; |
1939 |
> |
if (e != 0 && w != null) { |
1940 |
> |
Thread p; |
1941 |
|
long nc = ((long)(w.nextWait & E_MASK) | |
1942 |
|
(c & (AC_MASK|TC_MASK))); |
1943 |
< |
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
1944 |
< |
w.eventCount = (e + E_SEQ) & E_MASK; |
1943 |
> |
int ne = (e + E_SEQ) & E_MASK; |
1944 |
> |
if (w.eventCount == (e | INT_SIGN) && |
1945 |
> |
U.compareAndSwapLong(this, CTL, c, nc)) { |
1946 |
> |
w.eventCount = ne; |
1947 |
|
if ((p = w.parker) != null) |
1948 |
|
U.unpark(p); |
1949 |
|
return true; // replace with idle worker |
1986 |
|
*/ |
1987 |
|
final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) { |
1988 |
|
int s = 0; |
1989 |
< |
if (joiner != null && task != null && (s = task.status) >= 0) { |
1989 |
> |
if (task != null && (s = task.status) >= 0 && joiner != null) { |
1990 |
|
ForkJoinTask<?> prevJoin = joiner.currentJoin; |
1991 |
|
joiner.currentJoin = task; |
1992 |
< |
do {} while ((s = task.status) >= 0 && !joiner.isEmpty() && |
1993 |
< |
joiner.tryRemoveAndExec(task)); // process local tasks |
1994 |
< |
if (s >= 0 && (s = task.status) >= 0) { |
1995 |
< |
helpSignal(task, joiner.poolIndex, false); |
1996 |
< |
if ((s = task.status) >= 0 && |
2001 |
< |
(task instanceof CountedCompleter)) |
2002 |
< |
s = helpComplete(task, LIFO_QUEUE); |
2003 |
< |
} |
1992 |
> |
do {} while (joiner.tryRemoveAndExec(task) && // process local tasks |
1993 |
> |
(s = task.status) >= 0); |
1994 |
> |
if (s >= 0 && (task instanceof CountedCompleter)) |
1995 |
> |
s = helpComplete(joiner, (CountedCompleter<?>)task); |
1996 |
> |
long cc = 0; // for stability checks |
1997 |
|
while (s >= 0 && (s = task.status) >= 0) { |
1998 |
< |
if ((!joiner.isEmpty() || // try helping |
2006 |
< |
(s = tryHelpStealer(joiner, task)) == 0) && |
1998 |
> |
if ((s = tryHelpStealer(joiner, task)) == 0 && |
1999 |
|
(s = task.status) >= 0) { |
2000 |
< |
helpSignal(task, joiner.poolIndex, false); |
2001 |
< |
if ((s = task.status) >= 0 && tryCompensate()) { |
2000 |
> |
if (!tryCompensate(cc)) |
2001 |
> |
cc = ctl; |
2002 |
> |
else { |
2003 |
|
if (task.trySetSignal() && (s = task.status) >= 0) { |
2004 |
|
synchronized (task) { |
2005 |
|
if (task.status >= 0) { |
2012 |
|
task.notifyAll(); |
2013 |
|
} |
2014 |
|
} |
2015 |
< |
long c; // re-activate |
2015 |
> |
long c; // reactivate |
2016 |
|
do {} while (!U.compareAndSwapLong |
2017 |
< |
(this, CTL, c = ctl, c + AC_UNIT)); |
2017 |
> |
(this, CTL, c = ctl, |
2018 |
> |
((c & ~AC_MASK) | |
2019 |
> |
((c & AC_MASK) + AC_UNIT)))); |
2020 |
|
} |
2021 |
|
} |
2022 |
|
} |
2038 |
|
if (joiner != null && task != null && (s = task.status) >= 0) { |
2039 |
|
ForkJoinTask<?> prevJoin = joiner.currentJoin; |
2040 |
|
joiner.currentJoin = task; |
2041 |
< |
do {} while ((s = task.status) >= 0 && !joiner.isEmpty() && |
2042 |
< |
joiner.tryRemoveAndExec(task)); |
2043 |
< |
if (s >= 0 && (s = task.status) >= 0) { |
2044 |
< |
helpSignal(task, joiner.poolIndex, false); |
2045 |
< |
if ((s = task.status) >= 0 && |
2051 |
< |
(task instanceof CountedCompleter)) |
2052 |
< |
s = helpComplete(task, LIFO_QUEUE); |
2053 |
< |
} |
2054 |
< |
if (s >= 0 && joiner.isEmpty()) { |
2041 |
> |
do {} while (joiner.tryRemoveAndExec(task) && // process local tasks |
2042 |
> |
(s = task.status) >= 0); |
2043 |
> |
if (s >= 0) { |
2044 |
> |
if (task instanceof CountedCompleter) |
2045 |
> |
helpComplete(joiner, (CountedCompleter<?>)task); |
2046 |
|
do {} while (task.status >= 0 && |
2047 |
|
tryHelpStealer(joiner, task) > 0); |
2048 |
|
} |
2052 |
|
|
2053 |
|
/** |
2054 |
|
* Returns a (probably) non-empty steal queue, if one is found |
2055 |
< |
* during a random, then cyclic scan, else null. This method must |
2056 |
< |
* be retried by caller if, by the time it tries to use the queue, |
2057 |
< |
* it is empty. |
2058 |
< |
* @param r a (random) seed for scanning |
2059 |
< |
*/ |
2060 |
< |
private WorkQueue findNonEmptyStealQueue(int r) { |
2061 |
< |
for (WorkQueue[] ws;;) { |
2062 |
< |
int ps = plock, m, n; |
2063 |
< |
if ((ws = workQueues) == null || (m = ws.length - 1) < 1) |
2064 |
< |
return null; |
2065 |
< |
for (int j = (m + 1) << 2; ;) { |
2066 |
< |
WorkQueue q = ws[(((r + j) << 1) | 1) & m]; |
2076 |
< |
if (q != null && (n = q.base - q.top) < 0) { |
2077 |
< |
if (n < -1) |
2078 |
< |
signalWork(q); |
2079 |
< |
return q; |
2080 |
< |
} |
2081 |
< |
else if (--j < 0) { |
2082 |
< |
if (plock == ps) |
2083 |
< |
return null; |
2084 |
< |
break; |
2055 |
> |
* during a scan, else null. This method must be retried by |
2056 |
> |
* caller if, by the time it tries to use the queue, it is empty. |
2057 |
> |
*/ |
2058 |
> |
private WorkQueue findNonEmptyStealQueue() { |
2059 |
> |
int r = ThreadLocalRandom.current().nextInt(); |
2060 |
> |
for (;;) { |
2061 |
> |
int ps = plock, m; WorkQueue[] ws; WorkQueue q; |
2062 |
> |
if ((ws = workQueues) != null && (m = ws.length - 1) >= 0) { |
2063 |
> |
for (int j = (m + 1) << 2; j >= 0; --j) { |
2064 |
> |
if ((q = ws[(((r - j) << 1) | 1) & m]) != null && |
2065 |
> |
q.base - q.top < 0) |
2066 |
> |
return q; |
2067 |
|
} |
2068 |
|
} |
2069 |
+ |
if (plock == ps) |
2070 |
+ |
return null; |
2071 |
|
} |
2072 |
|
} |
2073 |
|
|
2078 |
|
* find tasks either. |
2079 |
|
*/ |
2080 |
|
final void helpQuiescePool(WorkQueue w) { |
2081 |
+ |
ForkJoinTask<?> ps = w.currentSteal; |
2082 |
|
for (boolean active = true;;) { |
2083 |
< |
ForkJoinTask<?> localTask; // exhaust local queue |
2084 |
< |
while ((localTask = w.nextLocalTask()) != null) |
2085 |
< |
localTask.doExec(); |
2086 |
< |
// Similar to loop in scan(), but ignoring submissions |
2102 |
< |
WorkQueue q = findNonEmptyStealQueue(w.nextSeed()); |
2103 |
< |
if (q != null) { |
2104 |
< |
ForkJoinTask<?> t; int b; |
2083 |
> |
long c; WorkQueue q; ForkJoinTask<?> t; int b; |
2084 |
> |
while ((t = w.nextLocalTask()) != null) |
2085 |
> |
t.doExec(); |
2086 |
> |
if ((q = findNonEmptyStealQueue()) != null) { |
2087 |
|
if (!active) { // re-establish active count |
2106 |
– |
long c; |
2088 |
|
active = true; |
2089 |
|
do {} while (!U.compareAndSwapLong |
2090 |
< |
(this, CTL, c = ctl, c + AC_UNIT)); |
2090 |
> |
(this, CTL, c = ctl, |
2091 |
> |
((c & ~AC_MASK) | |
2092 |
> |
((c & AC_MASK) + AC_UNIT)))); |
2093 |
> |
} |
2094 |
> |
if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null) { |
2095 |
> |
(w.currentSteal = t).doExec(); |
2096 |
> |
w.currentSteal = ps; |
2097 |
|
} |
2111 |
– |
if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null) |
2112 |
– |
w.runSubtask(t); |
2098 |
|
} |
2099 |
< |
else { |
2100 |
< |
long c; |
2101 |
< |
if (active) { // decrement active count without queuing |
2099 |
> |
else if (active) { // decrement active count without queuing |
2100 |
> |
long nc = ((c = ctl) & ~AC_MASK) | ((c & AC_MASK) - AC_UNIT); |
2101 |
> |
if ((int)(nc >> AC_SHIFT) + parallelism == 0) |
2102 |
> |
break; // bypass decrement-then-increment |
2103 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) |
2104 |
|
active = false; |
2118 |
– |
do {} while (!U.compareAndSwapLong |
2119 |
– |
(this, CTL, c = ctl, c -= AC_UNIT)); |
2120 |
– |
} |
2121 |
– |
else |
2122 |
– |
c = ctl; // re-increment on exit |
2123 |
– |
if ((int)(c >> AC_SHIFT) + (config & SMASK) == 0) { |
2124 |
– |
do {} while (!U.compareAndSwapLong |
2125 |
– |
(this, CTL, c = ctl, c + AC_UNIT)); |
2126 |
– |
break; |
2127 |
– |
} |
2105 |
|
} |
2106 |
+ |
else if ((int)((c = ctl) >> AC_SHIFT) + parallelism <= 0 && |
2107 |
+ |
U.compareAndSwapLong |
2108 |
+ |
(this, CTL, c, ((c & ~AC_MASK) | |
2109 |
+ |
((c & AC_MASK) + AC_UNIT)))) |
2110 |
+ |
break; |
2111 |
|
} |
2112 |
|
} |
2113 |
|
|
2121 |
|
WorkQueue q; int b; |
2122 |
|
if ((t = w.nextLocalTask()) != null) |
2123 |
|
return t; |
2124 |
< |
if ((q = findNonEmptyStealQueue(w.nextSeed())) == null) |
2124 |
> |
if ((q = findNonEmptyStealQueue()) == null) |
2125 |
|
return null; |
2126 |
|
if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null) |
2127 |
|
return t; |
2153 |
|
* producing extra tasks amortizes the uncertainty of progress and |
2154 |
|
* diffusion assumptions. |
2155 |
|
* |
2156 |
< |
* So, users will want to use values larger, but not much larger |
2156 |
> |
* So, users will want to use values larger (but not much larger) |
2157 |
|
* than 1 to both smooth over transient shortages and hedge |
2158 |
|
* against uneven progress; as traded off against the cost of |
2159 |
|
* extra task overhead. We leave the user to pick a threshold |
2177 |
|
static int getSurplusQueuedTaskCount() { |
2178 |
|
Thread t; ForkJoinWorkerThread wt; ForkJoinPool pool; WorkQueue q; |
2179 |
|
if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)) { |
2180 |
< |
int p = (pool = (wt = (ForkJoinWorkerThread)t).pool).config & SMASK; |
2180 |
> |
int p = (pool = (wt = (ForkJoinWorkerThread)t).pool).parallelism; |
2181 |
|
int n = (q = wt.workQueue).top - q.base; |
2182 |
|
int a = (int)(pool.ctl >> AC_SHIFT) + p; |
2183 |
|
return n - (a > (p >>>= 1) ? 0 : |
2206 |
|
* @return true if now terminating or terminated |
2207 |
|
*/ |
2208 |
|
private boolean tryTerminate(boolean now, boolean enable) { |
2209 |
< |
if (this == commonPool) // cannot shut down |
2209 |
> |
int ps; |
2210 |
> |
if (this == common) // cannot shut down |
2211 |
|
return false; |
2212 |
+ |
if ((ps = plock) >= 0) { // enable by setting plock |
2213 |
+ |
if (!enable) |
2214 |
+ |
return false; |
2215 |
+ |
if ((ps & PL_LOCK) != 0 || |
2216 |
+ |
!U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK)) |
2217 |
+ |
ps = acquirePlock(); |
2218 |
+ |
int nps = ((ps + PL_LOCK) & ~SHUTDOWN) | SHUTDOWN; |
2219 |
+ |
if (!U.compareAndSwapInt(this, PLOCK, ps, nps)) |
2220 |
+ |
releasePlock(nps); |
2221 |
+ |
} |
2222 |
|
for (long c;;) { |
2223 |
< |
if (((c = ctl) & STOP_BIT) != 0) { // already terminating |
2224 |
< |
if ((short)(c >>> TC_SHIFT) == -(config & SMASK)) { |
2223 |
> |
if (((c = ctl) & STOP_BIT) != 0) { // already terminating |
2224 |
> |
if ((short)(c >>> TC_SHIFT) + parallelism <= 0) { |
2225 |
|
synchronized (this) { |
2226 |
< |
notifyAll(); // signal when 0 workers |
2226 |
> |
notifyAll(); // signal when 0 workers |
2227 |
|
} |
2228 |
|
} |
2229 |
|
return true; |
2230 |
|
} |
2231 |
< |
if (plock >= 0) { // not yet enabled |
2232 |
< |
int ps; |
2233 |
< |
if (!enable) |
2241 |
< |
return false; |
2242 |
< |
if (((ps = plock) & PL_LOCK) != 0 || |
2243 |
< |
!U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK)) |
2244 |
< |
ps = acquirePlock(); |
2245 |
< |
int nps = SHUTDOWN; |
2246 |
< |
if (!U.compareAndSwapInt(this, PLOCK, ps, nps)) |
2247 |
< |
releasePlock(nps); |
2248 |
< |
} |
2249 |
< |
if (!now) { // check if idle & no tasks |
2250 |
< |
if ((int)(c >> AC_SHIFT) != -(config & SMASK) || |
2251 |
< |
hasQueuedSubmissions()) |
2231 |
> |
if (!now) { // check if idle & no tasks |
2232 |
> |
WorkQueue[] ws; WorkQueue w; |
2233 |
> |
if ((int)(c >> AC_SHIFT) + parallelism > 0) |
2234 |
|
return false; |
2235 |
< |
// Check for unqueued inactive workers. One pass suffices. |
2236 |
< |
WorkQueue[] ws = workQueues; WorkQueue w; |
2237 |
< |
if (ws != null) { |
2238 |
< |
for (int i = 1; i < ws.length; i += 2) { |
2239 |
< |
if ((w = ws[i]) != null && w.eventCount >= 0) |
2235 |
> |
if ((ws = workQueues) != null) { |
2236 |
> |
for (int i = 0; i < ws.length; ++i) { |
2237 |
> |
if ((w = ws[i]) != null && |
2238 |
> |
(!w.isEmpty() || |
2239 |
> |
((i & 1) != 0 && w.eventCount >= 0))) { |
2240 |
> |
signalWork(ws, w); |
2241 |
|
return false; |
2242 |
+ |
} |
2243 |
|
} |
2244 |
|
} |
2245 |
|
} |
2246 |
|
if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) { |
2247 |
|
for (int pass = 0; pass < 3; ++pass) { |
2248 |
< |
WorkQueue[] ws = workQueues; |
2249 |
< |
if (ws != null) { |
2266 |
< |
WorkQueue w; |
2248 |
> |
WorkQueue[] ws; WorkQueue w; Thread wt; |
2249 |
> |
if ((ws = workQueues) != null) { |
2250 |
|
int n = ws.length; |
2251 |
|
for (int i = 0; i < n; ++i) { |
2252 |
|
if ((w = ws[i]) != null) { |
2253 |
|
w.qlock = -1; |
2254 |
|
if (pass > 0) { |
2255 |
|
w.cancelAll(); |
2256 |
< |
if (pass > 1) |
2257 |
< |
w.interruptOwner(); |
2256 |
> |
if (pass > 1 && (wt = w.owner) != null) { |
2257 |
> |
if (!wt.isInterrupted()) { |
2258 |
> |
try { |
2259 |
> |
wt.interrupt(); |
2260 |
> |
} catch (Throwable ignore) { |
2261 |
> |
} |
2262 |
> |
} |
2263 |
> |
U.unpark(wt); |
2264 |
> |
} |
2265 |
|
} |
2266 |
|
} |
2267 |
|
} |
2268 |
|
// Wake up workers parked on event queue |
2269 |
|
int i, e; long cc; Thread p; |
2270 |
|
while ((e = (int)(cc = ctl) & E_MASK) != 0 && |
2271 |
< |
(i = e & SMASK) < n && |
2271 |
> |
(i = e & SMASK) < n && i >= 0 && |
2272 |
|
(w = ws[i]) != null) { |
2273 |
|
long nc = ((long)(w.nextWait & E_MASK) | |
2274 |
|
((cc + AC_UNIT) & AC_MASK) | |
2294 |
|
* least one task. |
2295 |
|
*/ |
2296 |
|
static WorkQueue commonSubmitterQueue() { |
2297 |
< |
ForkJoinPool p; WorkQueue[] ws; int m; Submitter z; |
2297 |
> |
Submitter z; ForkJoinPool p; WorkQueue[] ws; int m, r; |
2298 |
|
return ((z = submitters.get()) != null && |
2299 |
< |
(p = commonPool) != null && |
2299 |
> |
(p = common) != null && |
2300 |
|
(ws = p.workQueues) != null && |
2301 |
|
(m = ws.length - 1) >= 0) ? |
2302 |
|
ws[m & z.seed & SQMASK] : null; |
2305 |
|
/** |
2306 |
|
* Tries to pop the given task from submitter's queue in common pool. |
2307 |
|
*/ |
2308 |
< |
static boolean tryExternalUnpush(ForkJoinTask<?> t) { |
2309 |
< |
ForkJoinPool p; WorkQueue[] ws; WorkQueue q; Submitter z; |
2310 |
< |
ForkJoinTask<?>[] a; int m, s; |
2311 |
< |
if (t != null && |
2312 |
< |
(z = submitters.get()) != null && |
2313 |
< |
(p = commonPool) != null && |
2314 |
< |
(ws = p.workQueues) != null && |
2315 |
< |
(m = ws.length - 1) >= 0 && |
2316 |
< |
(q = ws[m & z.seed & SQMASK]) != null && |
2327 |
< |
(s = q.top) != q.base && |
2328 |
< |
(a = q.array) != null) { |
2308 |
> |
final boolean tryExternalUnpush(ForkJoinTask<?> task) { |
2309 |
> |
WorkQueue joiner; ForkJoinTask<?>[] a; int m, s; |
2310 |
> |
Submitter z = submitters.get(); |
2311 |
> |
WorkQueue[] ws = workQueues; |
2312 |
> |
boolean popped = false; |
2313 |
> |
if (z != null && ws != null && (m = ws.length - 1) >= 0 && |
2314 |
> |
(joiner = ws[z.seed & m & SQMASK]) != null && |
2315 |
> |
joiner.base != (s = joiner.top) && |
2316 |
> |
(a = joiner.array) != null) { |
2317 |
|
long j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE; |
2318 |
< |
if (U.getObject(a, j) == t && |
2319 |
< |
U.compareAndSwapInt(q, QLOCK, 0, 1)) { |
2320 |
< |
if (q.array == a && q.top == s && // recheck |
2321 |
< |
U.compareAndSwapObject(a, j, t, null)) { |
2322 |
< |
q.top = s - 1; |
2323 |
< |
q.qlock = 0; |
2336 |
< |
return true; |
2318 |
> |
if (U.getObject(a, j) == task && |
2319 |
> |
U.compareAndSwapInt(joiner, QLOCK, 0, 1)) { |
2320 |
> |
if (joiner.top == s && joiner.array == a && |
2321 |
> |
U.compareAndSwapObject(a, j, task, null)) { |
2322 |
> |
joiner.top = s - 1; |
2323 |
> |
popped = true; |
2324 |
|
} |
2325 |
< |
q.qlock = 0; |
2325 |
> |
joiner.qlock = 0; |
2326 |
|
} |
2327 |
|
} |
2328 |
< |
return false; |
2328 |
> |
return popped; |
2329 |
|
} |
2330 |
|
|
2331 |
< |
/** |
2332 |
< |
* Tries to pop and run local tasks within the same computation |
2333 |
< |
* as the given root. On failure, tries to help complete from |
2334 |
< |
* other queues via helpComplete. |
2335 |
< |
*/ |
2336 |
< |
private void externalHelpComplete(WorkQueue q, ForkJoinTask<?> root) { |
2337 |
< |
ForkJoinTask<?>[] a; int m; |
2338 |
< |
if (q != null && (a = q.array) != null && (m = (a.length - 1)) >= 0 && |
2339 |
< |
root != null && root.status >= 0) { |
2340 |
< |
for (;;) { |
2341 |
< |
int s, u; Object o; CountedCompleter<?> task = null; |
2342 |
< |
if ((s = q.top) - q.base > 0) { |
2343 |
< |
long j = ((m & (s - 1)) << ASHIFT) + ABASE; |
2357 |
< |
if ((o = U.getObject(a, j)) != null && |
2358 |
< |
(o instanceof CountedCompleter)) { |
2359 |
< |
CountedCompleter<?> t = (CountedCompleter<?>)o, r = t; |
2360 |
< |
do { |
2361 |
< |
if (r == root) { |
2362 |
< |
if (U.compareAndSwapInt(q, QLOCK, 0, 1)) { |
2363 |
< |
if (q.array == a && q.top == s && |
2364 |
< |
U.compareAndSwapObject(a, j, t, null)) { |
2365 |
< |
q.top = s - 1; |
2366 |
< |
task = t; |
2367 |
< |
} |
2368 |
< |
q.qlock = 0; |
2369 |
< |
} |
2370 |
< |
break; |
2371 |
< |
} |
2372 |
< |
} while ((r = r.completer) != null); |
2373 |
< |
} |
2374 |
< |
} |
2375 |
< |
if (task != null) |
2376 |
< |
task.doExec(); |
2377 |
< |
if (root.status < 0 || |
2378 |
< |
(u = (int)(ctl >>> 32)) >= 0 || (u >> UAC_SHIFT) >= 0) |
2331 |
> |
final int externalHelpComplete(CountedCompleter<?> task) { |
2332 |
> |
WorkQueue joiner; int m, j; |
2333 |
> |
Submitter z = submitters.get(); |
2334 |
> |
WorkQueue[] ws = workQueues; |
2335 |
> |
int s = 0; |
2336 |
> |
if (z != null && ws != null && (m = ws.length - 1) >= 0 && |
2337 |
> |
(joiner = ws[(j = z.seed) & m & SQMASK]) != null && task != null) { |
2338 |
> |
int scans = m + m + 1; |
2339 |
> |
long c = 0L; // for stability check |
2340 |
> |
j |= 1; // poll odd queues |
2341 |
> |
for (int k = scans; ; j += 2) { |
2342 |
> |
WorkQueue q; |
2343 |
> |
if ((s = task.status) < 0) |
2344 |
|
break; |
2345 |
< |
if (task == null) { |
2346 |
< |
helpSignal(root, q.poolIndex, false); |
2347 |
< |
if (root.status >= 0) |
2383 |
< |
helpComplete(root, SHARED_QUEUE); |
2345 |
> |
else if (joiner.externalPopAndExecCC(task)) |
2346 |
> |
k = scans; |
2347 |
> |
else if ((s = task.status) < 0) |
2348 |
|
break; |
2349 |
+ |
else if ((q = ws[j & m]) != null && q.pollAndExecCC(task)) |
2350 |
+ |
k = scans; |
2351 |
+ |
else if (--k < 0) { |
2352 |
+ |
if (c == (c = ctl)) |
2353 |
+ |
break; |
2354 |
+ |
k = scans; |
2355 |
|
} |
2356 |
|
} |
2357 |
|
} |
2358 |
< |
} |
2389 |
< |
|
2390 |
< |
/** |
2391 |
< |
* Tries to help execute or signal availability of the given task |
2392 |
< |
* from submitter's queue in common pool. |
2393 |
< |
*/ |
2394 |
< |
static void externalHelpJoin(ForkJoinTask<?> t) { |
2395 |
< |
// Some hard-to-avoid overlap with tryExternalUnpush |
2396 |
< |
ForkJoinPool p; WorkQueue[] ws; WorkQueue q, w; Submitter z; |
2397 |
< |
ForkJoinTask<?>[] a; int m, s, n; |
2398 |
< |
if (t != null && |
2399 |
< |
(z = submitters.get()) != null && |
2400 |
< |
(p = commonPool) != null && |
2401 |
< |
(ws = p.workQueues) != null && |
2402 |
< |
(m = ws.length - 1) >= 0 && |
2403 |
< |
(q = ws[m & z.seed & SQMASK]) != null && |
2404 |
< |
(a = q.array) != null) { |
2405 |
< |
int am = a.length - 1; |
2406 |
< |
if ((s = q.top) != q.base) { |
2407 |
< |
long j = ((am & (s - 1)) << ASHIFT) + ABASE; |
2408 |
< |
if (U.getObject(a, j) == t && |
2409 |
< |
U.compareAndSwapInt(q, QLOCK, 0, 1)) { |
2410 |
< |
if (q.array == a && q.top == s && |
2411 |
< |
U.compareAndSwapObject(a, j, t, null)) { |
2412 |
< |
q.top = s - 1; |
2413 |
< |
q.qlock = 0; |
2414 |
< |
t.doExec(); |
2415 |
< |
} |
2416 |
< |
else |
2417 |
< |
q.qlock = 0; |
2418 |
< |
} |
2419 |
< |
} |
2420 |
< |
if (t.status >= 0) { |
2421 |
< |
if (t instanceof CountedCompleter) |
2422 |
< |
p.externalHelpComplete(q, t); |
2423 |
< |
else |
2424 |
< |
p.helpSignal(t, q.poolIndex, false); |
2425 |
< |
} |
2426 |
< |
} |
2427 |
< |
} |
2428 |
< |
|
2429 |
< |
/** |
2430 |
< |
* Restricted version of helpQuiescePool for external callers |
2431 |
< |
*/ |
2432 |
< |
static void externalHelpQuiescePool() { |
2433 |
< |
ForkJoinPool p; ForkJoinTask<?> t; WorkQueue q; int b; |
2434 |
< |
if ((p = commonPool) != null && |
2435 |
< |
(q = p.findNonEmptyStealQueue(1)) != null && |
2436 |
< |
(b = q.base) - q.top < 0 && |
2437 |
< |
(t = q.pollAt(b)) != null) |
2438 |
< |
t.doExec(); |
2358 |
> |
return s; |
2359 |
|
} |
2360 |
|
|
2361 |
|
// Exported methods |
2374 |
|
* java.lang.RuntimePermission}{@code ("modifyThread")} |
2375 |
|
*/ |
2376 |
|
public ForkJoinPool() { |
2377 |
< |
this(Runtime.getRuntime().availableProcessors(), |
2377 |
> |
this(Math.min(MAX_CAP, Runtime.getRuntime().availableProcessors()), |
2378 |
|
defaultForkJoinWorkerThreadFactory, null, false); |
2379 |
|
} |
2380 |
|
|
2422 |
|
*/ |
2423 |
|
public ForkJoinPool(int parallelism, |
2424 |
|
ForkJoinWorkerThreadFactory factory, |
2425 |
< |
Thread.UncaughtExceptionHandler handler, |
2425 |
> |
UncaughtExceptionHandler handler, |
2426 |
|
boolean asyncMode) { |
2427 |
+ |
this(checkParallelism(parallelism), |
2428 |
+ |
checkFactory(factory), |
2429 |
+ |
handler, |
2430 |
+ |
(asyncMode ? FIFO_QUEUE : LIFO_QUEUE), |
2431 |
+ |
"ForkJoinPool-" + nextPoolId() + "-worker-"); |
2432 |
|
checkPermission(); |
2433 |
< |
if (factory == null) |
2434 |
< |
throw new NullPointerException(); |
2433 |
> |
} |
2434 |
> |
|
2435 |
> |
private static int checkParallelism(int parallelism) { |
2436 |
|
if (parallelism <= 0 || parallelism > MAX_CAP) |
2437 |
|
throw new IllegalArgumentException(); |
2438 |
< |
this.factory = factory; |
2439 |
< |
this.ueh = handler; |
2440 |
< |
this.config = parallelism | (asyncMode ? (FIFO_QUEUE << 16) : 0); |
2441 |
< |
long np = (long)(-parallelism); // offset ctl counts |
2442 |
< |
this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK); |
2443 |
< |
int pn = nextPoolId(); |
2444 |
< |
StringBuilder sb = new StringBuilder("ForkJoinPool-"); |
2445 |
< |
sb.append(Integer.toString(pn)); |
2520 |
< |
sb.append("-worker-"); |
2521 |
< |
this.workerNamePrefix = sb.toString(); |
2438 |
> |
return parallelism; |
2439 |
> |
} |
2440 |
> |
|
2441 |
> |
private static ForkJoinWorkerThreadFactory checkFactory |
2442 |
> |
(ForkJoinWorkerThreadFactory factory) { |
2443 |
> |
if (factory == null) |
2444 |
> |
throw new NullPointerException(); |
2445 |
> |
return factory; |
2446 |
|
} |
2447 |
|
|
2448 |
|
/** |
2449 |
< |
* Constructor for common pool, suitable only for static initialization. |
2450 |
< |
* Basically the same as above, but uses smallest possible initial footprint. |
2451 |
< |
*/ |
2452 |
< |
ForkJoinPool(int parallelism, long ctl, |
2453 |
< |
ForkJoinWorkerThreadFactory factory, |
2454 |
< |
Thread.UncaughtExceptionHandler handler) { |
2455 |
< |
this.config = parallelism; |
2456 |
< |
this.ctl = ctl; |
2449 |
> |
* Creates a {@code ForkJoinPool} with the given parameters, without |
2450 |
> |
* any security checks or parameter validation. Invoked directly by |
2451 |
> |
* makeCommonPool. |
2452 |
> |
*/ |
2453 |
> |
private ForkJoinPool(int parallelism, |
2454 |
> |
ForkJoinWorkerThreadFactory factory, |
2455 |
> |
UncaughtExceptionHandler handler, |
2456 |
> |
int mode, |
2457 |
> |
String workerNamePrefix) { |
2458 |
> |
this.workerNamePrefix = workerNamePrefix; |
2459 |
|
this.factory = factory; |
2460 |
|
this.ueh = handler; |
2461 |
< |
this.workerNamePrefix = "ForkJoinPool.commonPool-worker-"; |
2461 |
> |
this.mode = (short)mode; |
2462 |
> |
this.parallelism = (short)parallelism; |
2463 |
> |
long np = (long)(-parallelism); // offset ctl counts |
2464 |
> |
this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK); |
2465 |
|
} |
2466 |
|
|
2467 |
|
/** |
2468 |
< |
* Returns the common pool instance. |
2468 |
> |
* Returns the common pool instance. This pool is statically |
2469 |
> |
* constructed; its run state is unaffected by attempts to {@link |
2470 |
> |
* #shutdown} or {@link #shutdownNow}. However this pool and any |
2471 |
> |
* ongoing processing are automatically terminated upon program |
2472 |
> |
* {@link System#exit}. Any program that relies on asynchronous |
2473 |
> |
* task processing to complete before program termination should |
2474 |
> |
* invoke {@code commonPool().}{@link #awaitQuiescence awaitQuiescence}, |
2475 |
> |
* before exit. |
2476 |
|
* |
2477 |
|
* @return the common pool instance |
2478 |
+ |
* @since 1.8 |
2479 |
|
*/ |
2480 |
|
public static ForkJoinPool commonPool() { |
2481 |
< |
// assert commonPool != null : "static init error"; |
2482 |
< |
return commonPool; |
2481 |
> |
// assert common != null : "static init error"; |
2482 |
> |
return common; |
2483 |
|
} |
2484 |
|
|
2485 |
|
// Execution methods |
2495 |
|
* minimally only the latter. |
2496 |
|
* |
2497 |
|
* @param task the task |
2498 |
+ |
* @param <T> the type of the task's result |
2499 |
|
* @return the task's result |
2500 |
|
* @throws NullPointerException if the task is null |
2501 |
|
* @throws RejectedExecutionException if the task cannot be |
2536 |
|
if (task instanceof ForkJoinTask<?>) // avoid re-wrap |
2537 |
|
job = (ForkJoinTask<?>) task; |
2538 |
|
else |
2539 |
< |
job = new ForkJoinTask.AdaptedRunnableAction(task); |
2539 |
> |
job = new ForkJoinTask.RunnableExecuteAction(task); |
2540 |
|
externalPush(job); |
2541 |
|
} |
2542 |
|
|
2544 |
|
* Submits a ForkJoinTask for execution. |
2545 |
|
* |
2546 |
|
* @param task the task to submit |
2547 |
+ |
* @param <T> the type of the task's result |
2548 |
|
* @return the task |
2549 |
|
* @throws NullPointerException if the task is null |
2550 |
|
* @throws RejectedExecutionException if the task cannot be |
2604 |
|
// In previous versions of this class, this method constructed |
2605 |
|
// a task to run ForkJoinTask.invokeAll, but now external |
2606 |
|
// invocation of multiple tasks is at least as efficient. |
2607 |
< |
List<ForkJoinTask<T>> fs = new ArrayList<ForkJoinTask<T>>(tasks.size()); |
2669 |
< |
// Workaround needed because method wasn't declared with |
2670 |
< |
// wildcards in return type but should have been. |
2671 |
< |
@SuppressWarnings({"unchecked", "rawtypes"}) |
2672 |
< |
List<Future<T>> futures = (List<Future<T>>) (List) fs; |
2607 |
> |
ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size()); |
2608 |
|
|
2609 |
|
boolean done = false; |
2610 |
|
try { |
2611 |
|
for (Callable<T> t : tasks) { |
2612 |
|
ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t); |
2613 |
+ |
futures.add(f); |
2614 |
|
externalPush(f); |
2679 |
– |
fs.add(f); |
2615 |
|
} |
2616 |
< |
for (ForkJoinTask<T> f : fs) |
2617 |
< |
f.quietlyJoin(); |
2616 |
> |
for (int i = 0, size = futures.size(); i < size; i++) |
2617 |
> |
((ForkJoinTask<?>)futures.get(i)).quietlyJoin(); |
2618 |
|
done = true; |
2619 |
|
return futures; |
2620 |
|
} finally { |
2621 |
|
if (!done) |
2622 |
< |
for (ForkJoinTask<T> f : fs) |
2623 |
< |
f.cancel(false); |
2622 |
> |
for (int i = 0, size = futures.size(); i < size; i++) |
2623 |
> |
futures.get(i).cancel(false); |
2624 |
|
} |
2625 |
|
} |
2626 |
|
|
2639 |
|
* |
2640 |
|
* @return the handler, or {@code null} if none |
2641 |
|
*/ |
2642 |
< |
public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() { |
2642 |
> |
public UncaughtExceptionHandler getUncaughtExceptionHandler() { |
2643 |
|
return ueh; |
2644 |
|
} |
2645 |
|
|
2649 |
|
* @return the targeted parallelism level of this pool |
2650 |
|
*/ |
2651 |
|
public int getParallelism() { |
2652 |
< |
return config & SMASK; |
2652 |
> |
int par; |
2653 |
> |
return ((par = parallelism) > 0) ? par : 1; |
2654 |
|
} |
2655 |
|
|
2656 |
|
/** |
2657 |
|
* Returns the targeted parallelism level of the common pool. |
2658 |
|
* |
2659 |
|
* @return the targeted parallelism level of the common pool |
2660 |
+ |
* @since 1.8 |
2661 |
|
*/ |
2662 |
|
public static int getCommonPoolParallelism() { |
2663 |
< |
return commonPoolParallelism; |
2663 |
> |
return commonParallelism; |
2664 |
|
} |
2665 |
|
|
2666 |
|
/** |
2672 |
|
* @return the number of worker threads |
2673 |
|
*/ |
2674 |
|
public int getPoolSize() { |
2675 |
< |
return (config & SMASK) + (short)(ctl >>> TC_SHIFT); |
2675 |
> |
return parallelism + (short)(ctl >>> TC_SHIFT); |
2676 |
|
} |
2677 |
|
|
2678 |
|
/** |
2682 |
|
* @return {@code true} if this pool uses async mode |
2683 |
|
*/ |
2684 |
|
public boolean getAsyncMode() { |
2685 |
< |
return (config >>> 16) == FIFO_QUEUE; |
2685 |
> |
return mode == FIFO_QUEUE; |
2686 |
|
} |
2687 |
|
|
2688 |
|
/** |
2713 |
|
* @return the number of active threads |
2714 |
|
*/ |
2715 |
|
public int getActiveThreadCount() { |
2716 |
< |
int r = (config & SMASK) + (int)(ctl >> AC_SHIFT); |
2716 |
> |
int r = parallelism + (int)(ctl >> AC_SHIFT); |
2717 |
|
return (r <= 0) ? 0 : r; // suppress momentarily negative values |
2718 |
|
} |
2719 |
|
|
2729 |
|
* @return {@code true} if all threads are currently idle |
2730 |
|
*/ |
2731 |
|
public boolean isQuiescent() { |
2732 |
< |
return (int)(ctl >> AC_SHIFT) + (config & SMASK) == 0; |
2732 |
> |
return parallelism + (int)(ctl >> AC_SHIFT) <= 0; |
2733 |
|
} |
2734 |
|
|
2735 |
|
/** |
2892 |
|
} |
2893 |
|
} |
2894 |
|
} |
2895 |
< |
int pc = (config & SMASK); |
2895 |
> |
int pc = parallelism; |
2896 |
|
int tc = pc + (short)(c >>> TC_SHIFT); |
2897 |
|
int ac = pc + (int)(c >> AC_SHIFT); |
2898 |
|
if (ac < 0) // ignore transient negative |
2918 |
|
* Possibly initiates an orderly shutdown in which previously |
2919 |
|
* submitted tasks are executed, but no new tasks will be |
2920 |
|
* accepted. Invocation has no effect on execution state if this |
2921 |
< |
* is the {@link #commonPool}, and no additional effect if |
2921 |
> |
* is the {@link #commonPool()}, and no additional effect if |
2922 |
|
* already shut down. Tasks that are in the process of being |
2923 |
|
* submitted concurrently during the course of this method may or |
2924 |
|
* may not be rejected. |
2936 |
|
/** |
2937 |
|
* Possibly attempts to cancel and/or stop all tasks, and reject |
2938 |
|
* all subsequently submitted tasks. Invocation has no effect on |
2939 |
< |
* execution state if this is the {@link #commonPool}, and no |
2939 |
> |
* execution state if this is the {@link #commonPool()}, and no |
2940 |
|
* additional effect if already shut down. Otherwise, tasks that |
2941 |
|
* are in the process of being submitted or executed concurrently |
2942 |
|
* during the course of this method may or may not be |
2965 |
|
public boolean isTerminated() { |
2966 |
|
long c = ctl; |
2967 |
|
return ((c & STOP_BIT) != 0L && |
2968 |
< |
(short)(c >>> TC_SHIFT) == -(config & SMASK)); |
2968 |
> |
(short)(c >>> TC_SHIFT) + parallelism <= 0); |
2969 |
|
} |
2970 |
|
|
2971 |
|
/** |
2973 |
|
* commenced but not yet completed. This method may be useful for |
2974 |
|
* debugging. A return of {@code true} reported a sufficient |
2975 |
|
* period after shutdown may indicate that submitted tasks have |
2976 |
< |
* ignored or suppressed interruption, or are waiting for IO, |
2976 |
> |
* ignored or suppressed interruption, or are waiting for I/O, |
2977 |
|
* causing this executor not to properly terminate. (See the |
2978 |
|
* advisory notes for class {@link ForkJoinTask} stating that |
2979 |
|
* tasks should not normally entail blocking operations. But if |
2984 |
|
public boolean isTerminating() { |
2985 |
|
long c = ctl; |
2986 |
|
return ((c & STOP_BIT) != 0L && |
2987 |
< |
(short)(c >>> TC_SHIFT) != -(config & SMASK)); |
2987 |
> |
(short)(c >>> TC_SHIFT) + parallelism > 0); |
2988 |
|
} |
2989 |
|
|
2990 |
|
/** |
2999 |
|
/** |
3000 |
|
* Blocks until all tasks have completed execution after a |
3001 |
|
* shutdown request, or the timeout occurs, or the current thread |
3002 |
< |
* is interrupted, whichever happens first. Note that the {@link |
3003 |
< |
* #commonPool()} never terminates until program shutdown so |
3004 |
< |
* this method will always time out. |
3002 |
> |
* is interrupted, whichever happens first. Because the {@link |
3003 |
> |
* #commonPool()} never terminates until program shutdown, when |
3004 |
> |
* applied to the common pool, this method is equivalent to {@link |
3005 |
> |
* #awaitQuiescence(long, TimeUnit)} but always returns {@code false}. |
3006 |
|
* |
3007 |
|
* @param timeout the maximum time to wait |
3008 |
|
* @param unit the time unit of the timeout argument |
3012 |
|
*/ |
3013 |
|
public boolean awaitTermination(long timeout, TimeUnit unit) |
3014 |
|
throws InterruptedException { |
3015 |
+ |
if (Thread.interrupted()) |
3016 |
+ |
throw new InterruptedException(); |
3017 |
+ |
if (this == common) { |
3018 |
+ |
awaitQuiescence(timeout, unit); |
3019 |
+ |
return false; |
3020 |
+ |
} |
3021 |
|
long nanos = unit.toNanos(timeout); |
3022 |
|
if (isTerminated()) |
3023 |
|
return true; |
3024 |
< |
long startTime = System.nanoTime(); |
3025 |
< |
boolean terminated = false; |
3024 |
> |
if (nanos <= 0L) |
3025 |
> |
return false; |
3026 |
> |
long deadline = System.nanoTime() + nanos; |
3027 |
|
synchronized (this) { |
3028 |
< |
for (long waitTime = nanos, millis = 0L;;) { |
3029 |
< |
if (terminated = isTerminated() || |
3030 |
< |
waitTime <= 0L || |
3031 |
< |
(millis = unit.toMillis(waitTime)) <= 0L) |
3028 |
> |
for (;;) { |
3029 |
> |
if (isTerminated()) |
3030 |
> |
return true; |
3031 |
> |
if (nanos <= 0L) |
3032 |
> |
return false; |
3033 |
> |
long millis = TimeUnit.NANOSECONDS.toMillis(nanos); |
3034 |
> |
wait(millis > 0L ? millis : 1L); |
3035 |
> |
nanos = deadline - System.nanoTime(); |
3036 |
> |
} |
3037 |
> |
} |
3038 |
> |
} |
3039 |
> |
|
3040 |
> |
/** |
3041 |
> |
* If called by a ForkJoinTask operating in this pool, equivalent |
3042 |
> |
* in effect to {@link ForkJoinTask#helpQuiesce}. Otherwise, |
3043 |
> |
* waits and/or attempts to assist performing tasks until this |
3044 |
> |
* pool {@link #isQuiescent} or the indicated timeout elapses. |
3045 |
> |
* |
3046 |
> |
* @param timeout the maximum time to wait |
3047 |
> |
* @param unit the time unit of the timeout argument |
3048 |
> |
* @return {@code true} if quiescent; {@code false} if the |
3049 |
> |
* timeout elapsed. |
3050 |
> |
*/ |
3051 |
> |
public boolean awaitQuiescence(long timeout, TimeUnit unit) { |
3052 |
> |
long nanos = unit.toNanos(timeout); |
3053 |
> |
ForkJoinWorkerThread wt; |
3054 |
> |
Thread thread = Thread.currentThread(); |
3055 |
> |
if ((thread instanceof ForkJoinWorkerThread) && |
3056 |
> |
(wt = (ForkJoinWorkerThread)thread).pool == this) { |
3057 |
> |
helpQuiescePool(wt.workQueue); |
3058 |
> |
return true; |
3059 |
> |
} |
3060 |
> |
long startTime = System.nanoTime(); |
3061 |
> |
WorkQueue[] ws; |
3062 |
> |
int r = 0, m; |
3063 |
> |
boolean found = true; |
3064 |
> |
while (!isQuiescent() && (ws = workQueues) != null && |
3065 |
> |
(m = ws.length - 1) >= 0) { |
3066 |
> |
if (!found) { |
3067 |
> |
if ((System.nanoTime() - startTime) > nanos) |
3068 |
> |
return false; |
3069 |
> |
Thread.yield(); // cannot block |
3070 |
> |
} |
3071 |
> |
found = false; |
3072 |
> |
for (int j = (m + 1) << 2; j >= 0; --j) { |
3073 |
> |
ForkJoinTask<?> t; WorkQueue q; int b; |
3074 |
> |
if ((q = ws[r++ & m]) != null && (b = q.base) - q.top < 0) { |
3075 |
> |
found = true; |
3076 |
> |
if ((t = q.pollAt(b)) != null) |
3077 |
> |
t.doExec(); |
3078 |
|
break; |
3079 |
< |
wait(millis); |
3089 |
< |
waitTime = nanos - (System.nanoTime() - startTime); |
3079 |
> |
} |
3080 |
|
} |
3081 |
|
} |
3082 |
< |
return terminated; |
3082 |
> |
return true; |
3083 |
> |
} |
3084 |
> |
|
3085 |
> |
/** |
3086 |
> |
* Waits and/or attempts to assist performing tasks indefinitely |
3087 |
> |
* until the {@link #commonPool()} {@link #isQuiescent}. |
3088 |
> |
*/ |
3089 |
> |
static void quiesceCommonPool() { |
3090 |
> |
common.awaitQuiescence(Long.MAX_VALUE, TimeUnit.NANOSECONDS); |
3091 |
|
} |
3092 |
|
|
3093 |
|
/** |
3099 |
|
* not necessary. Method {@code block} blocks the current thread |
3100 |
|
* if necessary (perhaps internally invoking {@code isReleasable} |
3101 |
|
* before actually blocking). These actions are performed by any |
3102 |
< |
* thread invoking {@link ForkJoinPool#managedBlock}. The |
3103 |
< |
* unusual methods in this API accommodate synchronizers that may, |
3104 |
< |
* but don't usually, block for long periods. Similarly, they |
3102 |
> |
* thread invoking {@link ForkJoinPool#managedBlock(ManagedBlocker)}. |
3103 |
> |
* The unusual methods in this API accommodate synchronizers that |
3104 |
> |
* may, but don't usually, block for long periods. Similarly, they |
3105 |
|
* allow more efficient internal handling of cases in which |
3106 |
|
* additional workers may be, but usually are not, needed to |
3107 |
|
* ensure sufficient parallelism. Toward this end, |
3159 |
|
|
3160 |
|
/** |
3161 |
|
* Returns {@code true} if blocking is unnecessary. |
3162 |
+ |
* @return {@code true} if blocking is unnecessary |
3163 |
|
*/ |
3164 |
|
boolean isReleasable(); |
3165 |
|
} |
3189 |
|
Thread t = Thread.currentThread(); |
3190 |
|
if (t instanceof ForkJoinWorkerThread) { |
3191 |
|
ForkJoinPool p = ((ForkJoinWorkerThread)t).pool; |
3192 |
< |
while (!blocker.isReleasable()) { // variant of helpSignal |
3193 |
< |
WorkQueue[] ws; WorkQueue q; int m, u; |
3195 |
< |
if ((ws = p.workQueues) != null && (m = ws.length - 1) >= 0) { |
3196 |
< |
for (int i = 0; i <= m; ++i) { |
3197 |
< |
if (blocker.isReleasable()) |
3198 |
< |
return; |
3199 |
< |
if ((q = ws[i]) != null && q.base - q.top < 0) { |
3200 |
< |
p.signalWork(q); |
3201 |
< |
if ((u = (int)(p.ctl >>> 32)) >= 0 || |
3202 |
< |
(u >> UAC_SHIFT) >= 0) |
3203 |
< |
break; |
3204 |
< |
} |
3205 |
< |
} |
3206 |
< |
} |
3207 |
< |
if (p.tryCompensate()) { |
3192 |
> |
while (!blocker.isReleasable()) { |
3193 |
> |
if (p.tryCompensate(p.ctl)) { |
3194 |
|
try { |
3195 |
|
do {} while (!blocker.isReleasable() && |
3196 |
|
!blocker.block()); |
3228 |
|
private static final long STEALCOUNT; |
3229 |
|
private static final long PLOCK; |
3230 |
|
private static final long INDEXSEED; |
3231 |
+ |
private static final long QBASE; |
3232 |
|
private static final long QLOCK; |
3233 |
|
|
3234 |
|
static { |
3235 |
< |
int s; // initialize field offsets for CAS etc |
3235 |
> |
// initialize field offsets for CAS etc |
3236 |
|
try { |
3237 |
|
U = getUnsafe(); |
3238 |
|
Class<?> k = ForkJoinPool.class; |
3248 |
|
PARKBLOCKER = U.objectFieldOffset |
3249 |
|
(tk.getDeclaredField("parkBlocker")); |
3250 |
|
Class<?> wk = WorkQueue.class; |
3251 |
+ |
QBASE = U.objectFieldOffset |
3252 |
+ |
(wk.getDeclaredField("base")); |
3253 |
|
QLOCK = U.objectFieldOffset |
3254 |
|
(wk.getDeclaredField("qlock")); |
3255 |
|
Class<?> ak = ForkJoinTask[].class; |
3256 |
|
ABASE = U.arrayBaseOffset(ak); |
3257 |
< |
s = U.arrayIndexScale(ak); |
3258 |
< |
ASHIFT = 31 - Integer.numberOfLeadingZeros(s); |
3257 |
> |
int scale = U.arrayIndexScale(ak); |
3258 |
> |
if ((scale & (scale - 1)) != 0) |
3259 |
> |
throw new Error("data type scale not a power of two"); |
3260 |
> |
ASHIFT = 31 - Integer.numberOfLeadingZeros(scale); |
3261 |
|
} catch (Exception e) { |
3262 |
|
throw new Error(e); |
3263 |
|
} |
3273 |
– |
if ((s & (s-1)) != 0) |
3274 |
– |
throw new Error("data type scale not a power of two"); |
3264 |
|
|
3265 |
|
submitters = new ThreadLocal<Submitter>(); |
3266 |
< |
ForkJoinWorkerThreadFactory fac = defaultForkJoinWorkerThreadFactory = |
3266 |
> |
defaultForkJoinWorkerThreadFactory = |
3267 |
|
new DefaultForkJoinWorkerThreadFactory(); |
3268 |
|
modifyThreadPermission = new RuntimePermission("modifyThread"); |
3269 |
|
|
3270 |
< |
/* |
3271 |
< |
* Establish common pool parameters. For extra caution, |
3272 |
< |
* computations to set up common pool state are here; the |
3273 |
< |
* constructor just assigns these values to fields. |
3274 |
< |
*/ |
3270 |
> |
common = java.security.AccessController.doPrivileged |
3271 |
> |
(new java.security.PrivilegedAction<ForkJoinPool>() { |
3272 |
> |
public ForkJoinPool run() { return makeCommonPool(); }}); |
3273 |
> |
int par = common.parallelism; // report 1 even if threads disabled |
3274 |
> |
commonParallelism = par > 0 ? par : 1; |
3275 |
> |
} |
3276 |
|
|
3277 |
< |
int par = 0; |
3278 |
< |
Thread.UncaughtExceptionHandler handler = null; |
3279 |
< |
try { // TBD: limit or report ignored exceptions? |
3277 |
> |
/** |
3278 |
> |
* Creates and returns the common pool, respecting user settings |
3279 |
> |
* specified via system properties. |
3280 |
> |
*/ |
3281 |
> |
private static ForkJoinPool makeCommonPool() { |
3282 |
> |
int parallelism = -1; |
3283 |
> |
ForkJoinWorkerThreadFactory factory |
3284 |
> |
= defaultForkJoinWorkerThreadFactory; |
3285 |
> |
UncaughtExceptionHandler handler = null; |
3286 |
> |
try { // ignore exceptions in accessing/parsing properties |
3287 |
|
String pp = System.getProperty |
3288 |
|
("java.util.concurrent.ForkJoinPool.common.parallelism"); |
3292 |
– |
String hp = System.getProperty |
3293 |
– |
("java.util.concurrent.ForkJoinPool.common.exceptionHandler"); |
3289 |
|
String fp = System.getProperty |
3290 |
|
("java.util.concurrent.ForkJoinPool.common.threadFactory"); |
3291 |
+ |
String hp = System.getProperty |
3292 |
+ |
("java.util.concurrent.ForkJoinPool.common.exceptionHandler"); |
3293 |
+ |
if (pp != null) |
3294 |
+ |
parallelism = Integer.parseInt(pp); |
3295 |
|
if (fp != null) |
3296 |
< |
fac = ((ForkJoinWorkerThreadFactory)ClassLoader. |
3297 |
< |
getSystemClassLoader().loadClass(fp).newInstance()); |
3296 |
> |
factory = ((ForkJoinWorkerThreadFactory)ClassLoader. |
3297 |
> |
getSystemClassLoader().loadClass(fp).newInstance()); |
3298 |
|
if (hp != null) |
3299 |
< |
handler = ((Thread.UncaughtExceptionHandler)ClassLoader. |
3299 |
> |
handler = ((UncaughtExceptionHandler)ClassLoader. |
3300 |
|
getSystemClassLoader().loadClass(hp).newInstance()); |
3302 |
– |
if (pp != null) |
3303 |
– |
par = Integer.parseInt(pp); |
3301 |
|
} catch (Exception ignore) { |
3302 |
|
} |
3303 |
|
|
3304 |
< |
if (par <= 0) |
3305 |
< |
par = Runtime.getRuntime().availableProcessors(); |
3306 |
< |
if (par > MAX_CAP) |
3307 |
< |
par = MAX_CAP; |
3308 |
< |
commonPoolParallelism = par; |
3309 |
< |
long np = (long)(-par); // precompute initial ctl value |
3310 |
< |
long ct = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK); |
3314 |
< |
|
3315 |
< |
commonPool = new ForkJoinPool(par, ct, fac, handler); |
3304 |
> |
if (parallelism < 0 && // default 1 less than #cores |
3305 |
> |
(parallelism = Runtime.getRuntime().availableProcessors() - 1) < 0) |
3306 |
> |
parallelism = 0; |
3307 |
> |
if (parallelism > MAX_CAP) |
3308 |
> |
parallelism = MAX_CAP; |
3309 |
> |
return new ForkJoinPool(parallelism, factory, handler, LIFO_QUEUE, |
3310 |
> |
"ForkJoinPool.commonPool-worker-"); |
3311 |
|
} |
3312 |
|
|
3313 |
|
/** |
3320 |
|
private static sun.misc.Unsafe getUnsafe() { |
3321 |
|
try { |
3322 |
|
return sun.misc.Unsafe.getUnsafe(); |
3323 |
< |
} catch (SecurityException se) { |
3324 |
< |
try { |
3325 |
< |
return java.security.AccessController.doPrivileged |
3326 |
< |
(new java.security |
3327 |
< |
.PrivilegedExceptionAction<sun.misc.Unsafe>() { |
3328 |
< |
public sun.misc.Unsafe run() throws Exception { |
3329 |
< |
java.lang.reflect.Field f = sun.misc |
3330 |
< |
.Unsafe.class.getDeclaredField("theUnsafe"); |
3331 |
< |
f.setAccessible(true); |
3332 |
< |
return (sun.misc.Unsafe) f.get(null); |
3333 |
< |
}}); |
3334 |
< |
} catch (java.security.PrivilegedActionException e) { |
3335 |
< |
throw new RuntimeException("Could not initialize intrinsics", |
3336 |
< |
e.getCause()); |
3337 |
< |
} |
3323 |
> |
} catch (SecurityException tryReflectionInstead) {} |
3324 |
> |
try { |
3325 |
> |
return java.security.AccessController.doPrivileged |
3326 |
> |
(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() { |
3327 |
> |
public sun.misc.Unsafe run() throws Exception { |
3328 |
> |
Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class; |
3329 |
> |
for (java.lang.reflect.Field f : k.getDeclaredFields()) { |
3330 |
> |
f.setAccessible(true); |
3331 |
> |
Object x = f.get(null); |
3332 |
> |
if (k.isInstance(x)) |
3333 |
> |
return k.cast(x); |
3334 |
> |
} |
3335 |
> |
throw new NoSuchFieldError("the Unsafe"); |
3336 |
> |
}}); |
3337 |
> |
} catch (java.security.PrivilegedActionException e) { |
3338 |
> |
throw new RuntimeException("Could not initialize intrinsics", |
3339 |
> |
e.getCause()); |
3340 |
|
} |
3341 |
|
} |
3345 |
– |
|
3342 |
|
} |