5 |
|
*/ |
6 |
|
|
7 |
|
package jsr166y; |
8 |
< |
import java.util.*; |
8 |
> |
|
9 |
|
import java.util.concurrent.*; |
10 |
< |
import java.util.concurrent.atomic.*; |
11 |
< |
import java.util.concurrent.locks.*; |
12 |
< |
import sun.misc.Unsafe; |
13 |
< |
import java.lang.reflect.*; |
10 |
> |
|
11 |
> |
import java.util.Random; |
12 |
> |
import java.util.Collection; |
13 |
> |
import java.util.concurrent.locks.LockSupport; |
14 |
|
|
15 |
|
/** |
16 |
|
* A thread managed by a {@link ForkJoinPool}. This class is |
17 |
|
* subclassable solely for the sake of adding functionality -- there |
18 |
< |
* are no overridable methods dealing with scheduling or |
19 |
< |
* execution. However, you can override initialization and termination |
20 |
< |
* cleanup methods surrounding the main task processing loop. If you |
21 |
< |
* do create such a subclass, you will also need to supply a custom |
22 |
< |
* ForkJoinWorkerThreadFactory to use it in a ForkJoinPool. |
23 |
< |
* |
24 |
< |
* <p>This class also provides methods for generating per-thread |
25 |
< |
* random numbers, with the same properties as {@link |
26 |
< |
* java.util.Random} but with each generator isolated from those of |
27 |
< |
* other threads. |
18 |
> |
* are no overridable methods dealing with scheduling or execution. |
19 |
> |
* However, you can override initialization and termination methods |
20 |
> |
* surrounding the main task processing loop. If you do create such a |
21 |
> |
* subclass, you will also need to supply a custom {@link |
22 |
> |
* ForkJoinPool.ForkJoinWorkerThreadFactory} to use it in a {@code |
23 |
> |
* ForkJoinPool}. |
24 |
> |
* |
25 |
> |
* @since 1.7 |
26 |
> |
* @author Doug Lea |
27 |
|
*/ |
28 |
|
public class ForkJoinWorkerThread extends Thread { |
29 |
|
/* |
30 |
< |
* Algorithm overview: |
30 |
> |
* Overview: |
31 |
> |
* |
32 |
> |
* ForkJoinWorkerThreads are managed by ForkJoinPools and perform |
33 |
> |
* ForkJoinTasks. This class includes bookkeeping in support of |
34 |
> |
* worker activation, suspension, and lifecycle control described |
35 |
> |
* in more detail in the internal documentation of class |
36 |
> |
* ForkJoinPool. And as described further below, this class also |
37 |
> |
* includes special-cased support for some ForkJoinTask |
38 |
> |
* methods. But the main mechanics involve work-stealing: |
39 |
|
* |
40 |
< |
* 1. Work-Stealing: Work-stealing queues are special forms of |
41 |
< |
* Deques that support only three of the four possible |
42 |
< |
* end-operations -- push, pop, and deq (aka steal), and only do |
43 |
< |
* so under the constraints that push and pop are called only from |
44 |
< |
* the owning thread, while deq may be called from other threads. |
45 |
< |
* (If you are unfamiliar with them, you probably want to read |
46 |
< |
* Herlihy and Shavit's book "The Art of Multiprocessor |
47 |
< |
* programming", chapter 16 describing these in more detail before |
48 |
< |
* proceeding.) The main work-stealing queue design is roughly |
49 |
< |
* similar to "Dynamic Circular Work-Stealing Deque" by David |
50 |
< |
* Chase and Yossi Lev, SPAA 2005 |
51 |
< |
* (http://research.sun.com/scalable/pubs/index.html). The main |
52 |
< |
* difference ultimately stems from gc requirements that we null |
53 |
< |
* out taken slots as soon as we can, to maintain as small a |
54 |
< |
* footprint as possible even in programs generating huge numbers |
55 |
< |
* of tasks. To accomplish this, we shift the CAS arbitrating pop |
56 |
< |
* vs deq (steal) from being on the indices ("base" and "sp") to |
57 |
< |
* the slots themselves (mainly via method "casSlotNull()"). So, |
58 |
< |
* both a successful pop and deq mainly entail CAS'ing a nonnull |
59 |
< |
* slot to null. Because we rely on CASes of references, we do |
60 |
< |
* not need tag bits on base or sp. They are simple ints as used |
61 |
< |
* in any circular array-based queue (see for example ArrayDeque). |
62 |
< |
* Updates to the indices must still be ordered in a way that |
63 |
< |
* guarantees that (sp - base) > 0 means the queue is empty, but |
64 |
< |
* otherwise may err on the side of possibly making the queue |
65 |
< |
* appear nonempty when a push, pop, or deq have not fully |
66 |
< |
* committed. Note that this means that the deq operation, |
67 |
< |
* considered individually, is not wait-free. One thief cannot |
68 |
< |
* successfully continue until another in-progress one (or, if |
69 |
< |
* previously empty, a push) completes. However, in the |
70 |
< |
* aggregate, we ensure at least probablistic non-blockingness. If |
71 |
< |
* an attempted steal fails, a thief always chooses a different |
40 |
> |
* Work-stealing queues are special forms of Deques that support |
41 |
> |
* only three of the four possible end-operations -- push, pop, |
42 |
> |
* and deq (aka steal), under the further constraints that push |
43 |
> |
* and pop are called only from the owning thread, while deq may |
44 |
> |
* be called from other threads. (If you are unfamiliar with |
45 |
> |
* them, you probably want to read Herlihy and Shavit's book "The |
46 |
> |
* Art of Multiprocessor programming", chapter 16 describing these |
47 |
> |
* in more detail before proceeding.) The main work-stealing |
48 |
> |
* queue design is roughly similar to those in the papers "Dynamic |
49 |
> |
* Circular Work-Stealing Deque" by Chase and Lev, SPAA 2005 |
50 |
> |
* (http://research.sun.com/scalable/pubs/index.html) and |
51 |
> |
* "Idempotent work stealing" by Michael, Saraswat, and Vechev, |
52 |
> |
* PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186). |
53 |
> |
* The main differences ultimately stem from gc requirements that |
54 |
> |
* we null out taken slots as soon as we can, to maintain as small |
55 |
> |
* a footprint as possible even in programs generating huge |
56 |
> |
* numbers of tasks. To accomplish this, we shift the CAS |
57 |
> |
* arbitrating pop vs deq (steal) from being on the indices |
58 |
> |
* ("base" and "sp") to the slots themselves (mainly via method |
59 |
> |
* "casSlotNull()"). So, both a successful pop and deq mainly |
60 |
> |
* entail a CAS of a slot from non-null to null. Because we rely |
61 |
> |
* on CASes of references, we do not need tag bits on base or sp. |
62 |
> |
* They are simple ints as used in any circular array-based queue |
63 |
> |
* (see for example ArrayDeque). Updates to the indices must |
64 |
> |
* still be ordered in a way that guarantees that sp == base means |
65 |
> |
* the queue is empty, but otherwise may err on the side of |
66 |
> |
* possibly making the queue appear nonempty when a push, pop, or |
67 |
> |
* deq have not fully committed. Note that this means that the deq |
68 |
> |
* operation, considered individually, is not wait-free. One thief |
69 |
> |
* cannot successfully continue until another in-progress one (or, |
70 |
> |
* if previously empty, a push) completes. However, in the |
71 |
> |
* aggregate, we ensure at least probabilistic non-blockingness. |
72 |
> |
* If an attempted steal fails, a thief always chooses a different |
73 |
|
* random victim target to try next. So, in order for one thief to |
74 |
|
* progress, it suffices for any in-progress deq or new push on |
75 |
|
* any empty queue to complete. One reason this works well here is |
76 |
|
* that apparently-nonempty often means soon-to-be-stealable, |
77 |
< |
* which gives threads a chance to activate if necessary before |
78 |
< |
* stealing (see below). |
77 |
> |
* which gives threads a chance to set activation status if |
78 |
> |
* necessary before stealing. |
79 |
> |
* |
80 |
> |
* This approach also enables support for "async mode" where local |
81 |
> |
* task processing is in FIFO, not LIFO order; simply by using a |
82 |
> |
* version of deq rather than pop when locallyFifo is true (as set |
83 |
> |
* by the ForkJoinPool). This allows use in message-passing |
84 |
> |
* frameworks in which tasks are never joined. |
85 |
> |
* |
86 |
> |
* When a worker would otherwise be blocked waiting to join a |
87 |
> |
* task, it first tries a form of linear helping: Each worker |
88 |
> |
* records (in field currentSteal) the most recent task it stole |
89 |
> |
* from some other worker. Plus, it records (in field currentJoin) |
90 |
> |
* the task it is currently actively joining. Method joinTask uses |
91 |
> |
* these markers to try to find a worker to help (i.e., steal back |
92 |
> |
* a task from and execute it) that could hasten completion of the |
93 |
> |
* actively joined task. In essence, the joiner executes a task |
94 |
> |
* that would be on its own local deque had the to-be-joined task |
95 |
> |
* not been stolen. This may be seen as a conservative variant of |
96 |
> |
* the approach in Wagner & Calder "Leapfrogging: a portable |
97 |
> |
* technique for implementing efficient futures" SIGPLAN Notices, |
98 |
> |
* 1993 (http://portal.acm.org/citation.cfm?id=155354). It differs |
99 |
> |
* in that: (1) We only maintain dependency links across workers |
100 |
> |
* upon steals, rather than use per-task bookkeeping. This may |
101 |
> |
* require a linear scan of workers array to locate stealers, but |
102 |
> |
* usually doesn't because stealers leave hints (that may become |
103 |
> |
* stale/wrong) of where to locate them. This isolates cost to |
104 |
> |
* when it is needed, rather than adding to per-task overhead. |
105 |
> |
* (2) It is "shallow", ignoring nesting and potentially cyclic |
106 |
> |
* mutual steals. (3) It is intentionally racy: field currentJoin |
107 |
> |
* is updated only while actively joining, which means that we |
108 |
> |
* miss links in the chain during long-lived tasks, GC stalls etc |
109 |
> |
* (which is OK since blocking in such cases is usually a good |
110 |
> |
* idea). (4) We bound the number of attempts to find work (see |
111 |
> |
* MAX_HELP_DEPTH) and fall back to suspending the worker and if |
112 |
> |
* necessary replacing it with a spare (see |
113 |
> |
* ForkJoinPool.awaitJoin). |
114 |
|
* |
115 |
< |
* Efficient implementation of this approach currently relies on |
116 |
< |
* an uncomfortable amount of "Unsafe" mechanics. To maintain |
115 |
> |
* Efficient implementation of these algorithms currently relies |
116 |
> |
* on an uncomfortable amount of "Unsafe" mechanics. To maintain |
117 |
|
* correct orderings, reads and writes of variable base require |
118 |
< |
* volatile ordering. Variable sp does not require volatile write |
119 |
< |
* but needs cheaper store-ordering on writes. Because they are |
120 |
< |
* protected by volatile base reads, reads of the queue array and |
121 |
< |
* its slots do not need volatile load semantics, but writes (in |
122 |
< |
* push) require store order and CASes (in pop and deq) require |
123 |
< |
* (volatile) CAS semantics. Since these combinations aren't |
124 |
< |
* supported using ordinary volatiles, the only way to accomplish |
125 |
< |
* these effciently is to use direct Unsafe calls. (Using external |
126 |
< |
* AtomicIntegers and AtomicReferenceArrays for the indices and |
127 |
< |
* array is significantly slower because of memory locality and |
128 |
< |
* indirection effects.) Further, performance on most platforms is |
129 |
< |
* very sensitive to placement and sizing of the (resizable) queue |
130 |
< |
* array. Even though these queues don't usually become all that |
131 |
< |
* big, the initial size must be large enough to counteract cache |
118 |
> |
* volatile ordering. Variable sp does not require volatile |
119 |
> |
* writes but still needs store-ordering, which we accomplish by |
120 |
> |
* pre-incrementing sp before filling the slot with an ordered |
121 |
> |
* store. (Pre-incrementing also enables backouts used in |
122 |
> |
* joinTask.) Because they are protected by volatile base reads, |
123 |
> |
* reads of the queue array and its slots by other threads do not |
124 |
> |
* need volatile load semantics, but writes (in push) require |
125 |
> |
* store order and CASes (in pop and deq) require (volatile) CAS |
126 |
> |
* semantics. (Michael, Saraswat, and Vechev's algorithm has |
127 |
> |
* similar properties, but without support for nulling slots.) |
128 |
> |
* Since these combinations aren't supported using ordinary |
129 |
> |
* volatiles, the only way to accomplish these efficiently is to |
130 |
> |
* use direct Unsafe calls. (Using external AtomicIntegers and |
131 |
> |
* AtomicReferenceArrays for the indices and array is |
132 |
> |
* significantly slower because of memory locality and indirection |
133 |
> |
* effects.) |
134 |
> |
* |
135 |
> |
* Further, performance on most platforms is very sensitive to |
136 |
> |
* placement and sizing of the (resizable) queue array. Even |
137 |
> |
* though these queues don't usually become all that big, the |
138 |
> |
* initial size must be large enough to counteract cache |
139 |
|
* contention effects across multiple queues (especially in the |
140 |
|
* presence of GC cardmarking). Also, to improve thread-locality, |
141 |
< |
* queues are currently initialized immediately after the thread |
142 |
< |
* gets the initial signal to start processing tasks. However, |
143 |
< |
* all queue-related methods except pushTask are written in a way |
144 |
< |
* that allows them to instead be lazily allocated and/or disposed |
145 |
< |
* of when empty. All together, these low-level implementation |
146 |
< |
* choices produce as much as a factor of 4 performance |
147 |
< |
* improvement compared to naive implementations, and enable the |
148 |
< |
* processing of billions of tasks per second, sometimes at the |
149 |
< |
* expense of ugliness. |
150 |
< |
* |
151 |
< |
* 2. Run control: The primary run control is based on a global |
152 |
< |
* counter (activeCount) held by the pool. It uses an algorithm |
153 |
< |
* similar to that in Herlihy and Shavit section 17.6 to cause |
154 |
< |
* threads to eventually block when all threads declare they are |
155 |
< |
* inactive. (See variable "scans".) For this to work, threads |
156 |
< |
* must be declared active when executing tasks, and before |
157 |
< |
* stealing a task. They must be inactive before blocking on the |
158 |
< |
* Pool Barrier (awaiting a new submission or other Pool |
159 |
< |
* event). In between, there is some free play which we take |
160 |
< |
* advantage of to avoid contention and rapid flickering of the |
161 |
< |
* global activeCount: If inactive, we activate only if a victim |
162 |
< |
* queue appears to be nonempty (see above). Similarly, a thread |
113 |
< |
* tries to inactivate only after a full scan of other threads. |
114 |
< |
* The net effect is that contention on activeCount is rarely a |
115 |
< |
* measurable performance issue. (There are also a few other cases |
116 |
< |
* where we scan for work rather than retry/block upon |
117 |
< |
* contention.) |
118 |
< |
* |
119 |
< |
* 3. Selection control. We maintain policy of always choosing to |
120 |
< |
* run local tasks rather than stealing, and always trying to |
121 |
< |
* steal tasks before trying to run a new submission. All steals |
122 |
< |
* are currently performed in randomly-chosen deq-order. It may be |
123 |
< |
* worthwhile to bias these with locality / anti-locality |
124 |
< |
* information, but doing this well probably requires more |
125 |
< |
* lower-level information from JVMs than currently provided. |
141 |
> |
* queues are initialized after starting. All together, these |
142 |
> |
* low-level implementation choices produce as much as a factor of |
143 |
> |
* 4 performance improvement compared to naive implementations, |
144 |
> |
* and enable the processing of billions of tasks per second, |
145 |
> |
* sometimes at the expense of ugliness. |
146 |
> |
*/ |
147 |
> |
|
148 |
> |
/** |
149 |
> |
* Generator for initial random seeds for random victim |
150 |
> |
* selection. This is used only to create initial seeds. Random |
151 |
> |
* steals use a cheaper xorshift generator per steal attempt. We |
152 |
> |
* expect only rare contention on seedGenerator, so just use a |
153 |
> |
* plain Random. |
154 |
> |
*/ |
155 |
> |
private static final Random seedGenerator = new Random(); |
156 |
> |
|
157 |
> |
/** |
158 |
> |
* The maximum stolen->joining link depth allowed in helpJoinTask. |
159 |
> |
* Depths for legitimate chains are unbounded, but we use a fixed |
160 |
> |
* constant to avoid (otherwise unchecked) cycles and bound |
161 |
> |
* staleness of traversal parameters at the expense of sometimes |
162 |
> |
* blocking when we could be helping. |
163 |
|
*/ |
164 |
+ |
private static final int MAX_HELP_DEPTH = 8; |
165 |
|
|
166 |
|
/** |
167 |
|
* Capacity of work-stealing queue array upon initialization. |
168 |
< |
* Must be a power of two. Initial size must be at least 2, but is |
168 |
> |
* Must be a power of two. Initial size must be at least 4, but is |
169 |
|
* padded to minimize cache effects. |
170 |
|
*/ |
171 |
|
private static final int INITIAL_QUEUE_CAPACITY = 1 << 13; |
172 |
|
|
173 |
|
/** |
174 |
|
* Maximum work-stealing queue array size. Must be less than or |
175 |
< |
* equal to 1 << 30 to ensure lack of index wraparound. |
175 |
> |
* equal to 1 << (31 - width of array entry) to ensure lack of |
176 |
> |
* index wraparound. The value is set in the static block |
177 |
> |
* at the end of this file after obtaining width. |
178 |
|
*/ |
179 |
< |
private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 30; |
179 |
> |
private static final int MAXIMUM_QUEUE_CAPACITY; |
180 |
|
|
181 |
|
/** |
182 |
< |
* Generator of seeds for per-thread random numbers. |
182 |
> |
* The pool this thread works in. Accessed directly by ForkJoinTask. |
183 |
|
*/ |
184 |
< |
private static final Random randomSeedGenerator = new Random(); |
184 |
> |
final ForkJoinPool pool; |
185 |
|
|
186 |
|
/** |
187 |
|
* The work-stealing queue array. Size must be a power of two. |
188 |
+ |
* Initialized in onStart, to improve memory locality. |
189 |
|
*/ |
190 |
|
private ForkJoinTask<?>[] queue; |
191 |
|
|
192 |
|
/** |
193 |
+ |
* Index (mod queue.length) of least valid queue slot, which is |
194 |
+ |
* always the next position to steal from if nonempty. |
195 |
+ |
*/ |
196 |
+ |
private volatile int base; |
197 |
+ |
|
198 |
+ |
/** |
199 |
|
* Index (mod queue.length) of next queue slot to push to or pop |
200 |
< |
* from. It is written only by owner thread, via ordered store. |
201 |
< |
* Both sp and base are allowed to wrap around on overflow, but |
202 |
< |
* (sp - base) still estimates size. |
200 |
> |
* from. It is written only by owner thread, and accessed by other |
201 |
> |
* threads only after reading (volatile) base. Both sp and base |
202 |
> |
* are allowed to wrap around on overflow, but (sp - base) still |
203 |
> |
* estimates size. |
204 |
|
*/ |
205 |
< |
private volatile int sp; |
205 |
> |
private int sp; |
206 |
|
|
207 |
|
/** |
208 |
< |
* Index (mod queue.length) of least valid queue slot, which is |
209 |
< |
* always the next position to steal from if nonempty. |
208 |
> |
* The index of most recent stealer, used as a hint to avoid |
209 |
> |
* traversal in method helpJoinTask. This is only a hint because a |
210 |
> |
* worker might have had multiple steals and this only holds one |
211 |
> |
* of them (usually the most current). Declared non-volatile, |
212 |
> |
* relying on other prevailing sync to keep reasonably current. |
213 |
|
*/ |
214 |
< |
private volatile int base; |
214 |
> |
private int stealHint; |
215 |
|
|
216 |
|
/** |
217 |
< |
* The pool this thread works in. |
217 |
> |
* Run state of this worker. In addition to the usual run levels, |
218 |
> |
* tracks if this worker is suspended as a spare, and if it was |
219 |
> |
* killed (trimmed) while suspended. However, "active" status is |
220 |
> |
* maintained separately and modified only in conjunction with |
221 |
> |
* CASes of the pool's runState (which are currently sadly |
222 |
> |
* manually inlined for performance.) Accessed directly by pool |
223 |
> |
* to simplify checks for normal (zero) status. |
224 |
|
*/ |
225 |
< |
final ForkJoinPool pool; |
225 |
> |
volatile int runState; |
226 |
> |
|
227 |
> |
private static final int TERMINATING = 0x01; |
228 |
> |
private static final int TERMINATED = 0x02; |
229 |
> |
private static final int SUSPENDED = 0x04; // inactive spare |
230 |
> |
private static final int TRIMMED = 0x08; // killed while suspended |
231 |
> |
|
232 |
> |
/** |
233 |
> |
* Number of steals. Directly accessed (and reset) by |
234 |
> |
* pool.tryAccumulateStealCount when idle. |
235 |
> |
*/ |
236 |
> |
int stealCount; |
237 |
> |
|
238 |
> |
/** |
239 |
> |
* Seed for random number generator for choosing steal victims. |
240 |
> |
* Uses Marsaglia xorshift. Must be initialized as nonzero. |
241 |
> |
*/ |
242 |
> |
private int seed; |
243 |
> |
|
244 |
> |
/** |
245 |
> |
* Activity status. When true, this worker is considered active. |
246 |
> |
* Accessed directly by pool. Must be false upon construction. |
247 |
> |
*/ |
248 |
> |
boolean active; |
249 |
> |
|
250 |
> |
/** |
251 |
> |
* True if use local fifo, not default lifo, for local polling. |
252 |
> |
* Shadows value from ForkJoinPool. |
253 |
> |
*/ |
254 |
> |
private final boolean locallyFifo; |
255 |
|
|
256 |
|
/** |
257 |
|
* Index of this worker in pool array. Set once by pool before |
258 |
< |
* running, and accessed directly by pool during cleanup etc |
258 |
> |
* running, and accessed directly by pool to locate this worker in |
259 |
> |
* its workers array. |
260 |
|
*/ |
261 |
|
int poolIndex; |
262 |
|
|
263 |
|
/** |
264 |
< |
* Run state of this worker. Supports simple versions of the usual |
265 |
< |
* shutdown/shutdownNow control. |
264 |
> |
* The last pool event waited for. Accessed only by pool in |
265 |
> |
* callback methods invoked within this thread. |
266 |
|
*/ |
267 |
< |
private volatile int runState; |
181 |
< |
|
182 |
< |
// Runstate values. Order matters |
183 |
< |
private static final int RUNNING = 0; |
184 |
< |
private static final int SHUTDOWN = 1; |
185 |
< |
private static final int TERMINATING = 2; |
186 |
< |
private static final int TERMINATED = 3; |
267 |
> |
int lastEventCount; |
268 |
|
|
269 |
|
/** |
270 |
< |
* Activity status. When true, this worker is considered active. |
271 |
< |
* Must be false upon construction. It must be true when executing |
191 |
< |
* tasks, and BEFORE stealing a task. It must be false before |
192 |
< |
* blocking on the Pool Barrier. |
270 |
> |
* Encoded index and event count of next event waiter. Accessed |
271 |
> |
* only by ForkJoinPool for managing event waiters. |
272 |
|
*/ |
273 |
< |
private boolean active; |
273 |
> |
volatile long nextWaiter; |
274 |
|
|
275 |
|
/** |
276 |
< |
* Number of steals, transferred to pool when idle |
276 |
> |
* Number of times this thread suspended as spare. Accessed only |
277 |
> |
* by pool. |
278 |
|
*/ |
279 |
< |
private int stealCount; |
279 |
> |
int spareCount; |
280 |
|
|
281 |
|
/** |
282 |
< |
* Seed for random number generator for choosing steal victims |
282 |
> |
* Encoded index and count of next spare waiter. Accessed only |
283 |
> |
* by ForkJoinPool for managing spares. |
284 |
|
*/ |
285 |
< |
private int randomVictimSeed; |
285 |
> |
volatile int nextSpare; |
286 |
|
|
287 |
|
/** |
288 |
< |
* Seed for embedded Jurandom |
288 |
> |
* The task currently being joined, set only when actively trying |
289 |
> |
* to help other stealers in helpJoinTask. Written only by this |
290 |
> |
* thread, but read by others. |
291 |
|
*/ |
292 |
< |
private long juRandomSeed; |
292 |
> |
private volatile ForkJoinTask<?> currentJoin; |
293 |
|
|
294 |
|
/** |
295 |
< |
* The last barrier event waited for |
295 |
> |
* The task most recently stolen from another worker (or |
296 |
> |
* submission queue). Written only by this thread, but read by |
297 |
> |
* others. |
298 |
|
*/ |
299 |
< |
private long eventCount; |
299 |
> |
private volatile ForkJoinTask<?> currentSteal; |
300 |
|
|
301 |
|
/** |
302 |
|
* Creates a ForkJoinWorkerThread operating in the given pool. |
303 |
+ |
* |
304 |
|
* @param pool the pool this thread works in |
305 |
|
* @throws NullPointerException if pool is null |
306 |
|
*/ |
307 |
|
protected ForkJoinWorkerThread(ForkJoinPool pool) { |
222 |
– |
if (pool == null) throw new NullPointerException(); |
308 |
|
this.pool = pool; |
309 |
< |
// remaining initialization deferred to onStart |
309 |
> |
this.locallyFifo = pool.locallyFifo; |
310 |
> |
setDaemon(true); |
311 |
> |
// To avoid exposing construction details to subclasses, |
312 |
> |
// remaining initialization is in start() and onStart() |
313 |
|
} |
314 |
|
|
315 |
< |
// public access methods |
315 |
> |
/** |
316 |
> |
* Performs additional initialization and starts this thread. |
317 |
> |
*/ |
318 |
> |
final void start(int poolIndex, UncaughtExceptionHandler ueh) { |
319 |
> |
this.poolIndex = poolIndex; |
320 |
> |
if (ueh != null) |
321 |
> |
setUncaughtExceptionHandler(ueh); |
322 |
> |
start(); |
323 |
> |
} |
324 |
> |
|
325 |
> |
// Public/protected methods |
326 |
|
|
327 |
|
/** |
328 |
< |
* Returns the pool hosting the current task execution. |
328 |
> |
* Returns the pool hosting this thread. |
329 |
> |
* |
330 |
|
* @return the pool |
331 |
|
*/ |
332 |
< |
public static ForkJoinPool getPool() { |
333 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())).pool; |
332 |
> |
public ForkJoinPool getPool() { |
333 |
> |
return pool; |
334 |
|
} |
335 |
|
|
336 |
|
/** |
337 |
< |
* Returns the index number of the current worker thread in its |
338 |
< |
* pool. The returned value ranges from zero to the maximum |
339 |
< |
* number of threads (minus one) that have ever been created in |
340 |
< |
* the pool. This method may be useful for applications that |
341 |
< |
* track status or collect results on a per-worker basis. |
342 |
< |
* @return the index number. |
337 |
> |
* Returns the index number of this thread in its pool. The |
338 |
> |
* returned value ranges from zero to the maximum number of |
339 |
> |
* threads (minus one) that have ever been created in the pool. |
340 |
> |
* This method may be useful for applications that track status or |
341 |
> |
* collect results per-worker rather than per-task. |
342 |
> |
* |
343 |
> |
* @return the index number |
344 |
|
*/ |
345 |
< |
public static int getPoolIndex() { |
346 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())).poolIndex; |
345 |
> |
public int getPoolIndex() { |
346 |
> |
return poolIndex; |
347 |
|
} |
348 |
|
|
349 |
< |
// Access methods used by Pool |
349 |
> |
/** |
350 |
> |
* Initializes internal state after construction but before |
351 |
> |
* processing any tasks. If you override this method, you must |
352 |
> |
* invoke @code{super.onStart()} at the beginning of the method. |
353 |
> |
* Initialization requires care: Most fields must have legal |
354 |
> |
* default values, to ensure that attempted accesses from other |
355 |
> |
* threads work correctly even before this thread starts |
356 |
> |
* processing tasks. |
357 |
> |
*/ |
358 |
> |
protected void onStart() { |
359 |
> |
int rs = seedGenerator.nextInt(); |
360 |
> |
seed = rs == 0? 1 : rs; // seed must be nonzero |
361 |
> |
|
362 |
> |
// Allocate name string and arrays in this thread |
363 |
> |
String pid = Integer.toString(pool.getPoolNumber()); |
364 |
> |
String wid = Integer.toString(poolIndex); |
365 |
> |
setName("ForkJoinPool-" + pid + "-worker-" + wid); |
366 |
> |
|
367 |
> |
queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY]; |
368 |
> |
} |
369 |
|
|
370 |
|
/** |
371 |
< |
* Get and clear steal count for accumulation by pool. Called |
372 |
< |
* only when known to be idle (in pool.sync and termination). |
371 |
> |
* Performs cleanup associated with termination of this worker |
372 |
> |
* thread. If you override this method, you must invoke |
373 |
> |
* {@code super.onTermination} at the end of the overridden method. |
374 |
> |
* |
375 |
> |
* @param exception the exception causing this thread to abort due |
376 |
> |
* to an unrecoverable error, or {@code null} if completed normally |
377 |
|
*/ |
378 |
< |
final int getAndClearStealCount() { |
379 |
< |
int sc = stealCount; |
380 |
< |
stealCount = 0; |
381 |
< |
return sc; |
378 |
> |
protected void onTermination(Throwable exception) { |
379 |
> |
try { |
380 |
> |
ForkJoinPool p = pool; |
381 |
> |
if (active) { |
382 |
> |
int a; // inline p.tryDecrementActiveCount |
383 |
> |
active = false; |
384 |
> |
do {} while (!UNSAFE.compareAndSwapInt |
385 |
> |
(p, poolRunStateOffset, a = p.runState, a - 1)); |
386 |
> |
} |
387 |
> |
cancelTasks(); |
388 |
> |
setTerminated(); |
389 |
> |
p.workerTerminated(this); |
390 |
> |
} catch (Throwable ex) { // Shouldn't ever happen |
391 |
> |
if (exception == null) // but if so, at least rethrown |
392 |
> |
exception = ex; |
393 |
> |
} finally { |
394 |
> |
if (exception != null) |
395 |
> |
UNSAFE.throwException(exception); |
396 |
> |
} |
397 |
|
} |
398 |
|
|
399 |
|
/** |
400 |
< |
* Returns estimate of the number of tasks in the queue, without |
401 |
< |
* correcting for transient negative values |
400 |
> |
* This method is required to be public, but should never be |
401 |
> |
* called explicitly. It performs the main run loop to execute |
402 |
> |
* ForkJoinTasks. |
403 |
|
*/ |
404 |
< |
final int getRawQueueSize() { |
405 |
< |
return sp - base; |
404 |
> |
public void run() { |
405 |
> |
Throwable exception = null; |
406 |
> |
try { |
407 |
> |
onStart(); |
408 |
> |
mainLoop(); |
409 |
> |
} catch (Throwable ex) { |
410 |
> |
exception = ex; |
411 |
> |
} finally { |
412 |
> |
onTermination(exception); |
413 |
> |
} |
414 |
|
} |
415 |
|
|
416 |
< |
// Intrinsics-based support for queue operations. |
270 |
< |
// Currently these three (setSp, setSlot, casSlotNull) are |
271 |
< |
// usually manually inlined to improve performance |
416 |
> |
// helpers for run() |
417 |
|
|
418 |
|
/** |
419 |
< |
* Sets sp in store-order. |
419 |
> |
* Finds and executes tasks, and checks status while running. |
420 |
|
*/ |
421 |
< |
private void setSp(int s) { |
422 |
< |
_unsafe.putOrderedInt(this, spOffset, s); |
421 |
> |
private void mainLoop() { |
422 |
> |
boolean ran = false; // true if ran a task on last step |
423 |
> |
ForkJoinPool p = pool; |
424 |
> |
for (;;) { |
425 |
> |
p.preStep(this, ran); |
426 |
> |
if (runState != 0) |
427 |
> |
break; |
428 |
> |
ran = tryExecSteal() || tryExecSubmission(); |
429 |
> |
} |
430 |
> |
} |
431 |
> |
|
432 |
> |
/** |
433 |
> |
* Tries to steal a task and execute it. |
434 |
> |
* |
435 |
> |
* @return true if ran a task |
436 |
> |
*/ |
437 |
> |
private boolean tryExecSteal() { |
438 |
> |
ForkJoinTask<?> t; |
439 |
> |
if ((t = scan()) != null) { |
440 |
> |
t.quietlyExec(); |
441 |
> |
UNSAFE.putOrderedObject(this, currentStealOffset, null); |
442 |
> |
if (sp != base) |
443 |
> |
execLocalTasks(); |
444 |
> |
return true; |
445 |
> |
} |
446 |
> |
return false; |
447 |
> |
} |
448 |
> |
|
449 |
> |
/** |
450 |
> |
* If a submission exists, try to activate and run it. |
451 |
> |
* |
452 |
> |
* @return true if ran a task |
453 |
> |
*/ |
454 |
> |
private boolean tryExecSubmission() { |
455 |
> |
ForkJoinPool p = pool; |
456 |
> |
// This loop is needed in case attempt to activate fails, in |
457 |
> |
// which case we only retry if there still appears to be a |
458 |
> |
// submission. |
459 |
> |
while (p.hasQueuedSubmissions()) { |
460 |
> |
ForkJoinTask<?> t; int a; |
461 |
> |
if (active || // inline p.tryIncrementActiveCount |
462 |
> |
(active = UNSAFE.compareAndSwapInt(p, poolRunStateOffset, |
463 |
> |
a = p.runState, a + 1))) { |
464 |
> |
if ((t = p.pollSubmission()) != null) { |
465 |
> |
UNSAFE.putOrderedObject(this, currentStealOffset, t); |
466 |
> |
t.quietlyExec(); |
467 |
> |
UNSAFE.putOrderedObject(this, currentStealOffset, null); |
468 |
> |
if (sp != base) |
469 |
> |
execLocalTasks(); |
470 |
> |
return true; |
471 |
> |
} |
472 |
> |
} |
473 |
> |
} |
474 |
> |
return false; |
475 |
> |
} |
476 |
> |
|
477 |
> |
/** |
478 |
> |
* Runs local tasks until queue is empty or shut down. Call only |
479 |
> |
* while active. |
480 |
> |
*/ |
481 |
> |
private void execLocalTasks() { |
482 |
> |
while (runState == 0) { |
483 |
> |
ForkJoinTask<?> t = locallyFifo ? locallyDeqTask() : popTask(); |
484 |
> |
if (t != null) |
485 |
> |
t.quietlyExec(); |
486 |
> |
else if (sp == base) |
487 |
> |
break; |
488 |
> |
} |
489 |
|
} |
490 |
|
|
491 |
+ |
/* |
492 |
+ |
* Intrinsics-based atomic writes for queue slots. These are |
493 |
+ |
* basically the same as methods in AtomicReferenceArray, but |
494 |
+ |
* specialized for (1) ForkJoinTask elements (2) requirement that |
495 |
+ |
* nullness and bounds checks have already been performed by |
496 |
+ |
* callers and (3) effective offsets are known not to overflow |
497 |
+ |
* from int to long (because of MAXIMUM_QUEUE_CAPACITY). We don't |
498 |
+ |
* need corresponding version for reads: plain array reads are OK |
499 |
+ |
* because they are protected by other volatile reads and are |
500 |
+ |
* confirmed by CASes. |
501 |
+ |
* |
502 |
+ |
* Most uses don't actually call these methods, but instead contain |
503 |
+ |
* inlined forms that enable more predictable optimization. We |
504 |
+ |
* don't define the version of write used in pushTask at all, but |
505 |
+ |
* instead inline there a store-fenced array slot write. |
506 |
+ |
*/ |
507 |
+ |
|
508 |
|
/** |
509 |
< |
* Add in store-order the given task at given slot of q to |
510 |
< |
* null. Caller must ensure q is nonnull and index is in range. |
509 |
> |
* CASes slot i of array q from t to null. Caller must ensure q is |
510 |
> |
* non-null and index is in range. |
511 |
|
*/ |
512 |
< |
private static void setSlot(ForkJoinTask<?>[] q, int i, |
513 |
< |
ForkJoinTask<?> t){ |
514 |
< |
_unsafe.putOrderedObject(q, (i << qShift) + qBase, t); |
512 |
> |
private static final boolean casSlotNull(ForkJoinTask<?>[] q, int i, |
513 |
> |
ForkJoinTask<?> t) { |
514 |
> |
return UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null); |
515 |
|
} |
516 |
|
|
517 |
|
/** |
518 |
< |
* CAS given slot of q to null. Caller must ensure q is nonnull |
519 |
< |
* and index is in range. |
518 |
> |
* Performs a volatile write of the given task at given slot of |
519 |
> |
* array q. Caller must ensure q is non-null and index is in |
520 |
> |
* range. This method is used only during resets and backouts. |
521 |
|
*/ |
522 |
< |
private static boolean casSlotNull(ForkJoinTask<?>[] q, int i, |
523 |
< |
ForkJoinTask<?> t) { |
524 |
< |
return _unsafe.compareAndSwapObject(q, (i << qShift) + qBase, t, null); |
522 |
> |
private static final void writeSlot(ForkJoinTask<?>[] q, int i, |
523 |
> |
ForkJoinTask<?> t) { |
524 |
> |
UNSAFE.putObjectVolatile(q, (i << qShift) + qBase, t); |
525 |
|
} |
526 |
|
|
527 |
< |
// Main queue methods |
527 |
> |
// queue methods |
528 |
|
|
529 |
|
/** |
530 |
< |
* Pushes a task. Called only by current thread. |
531 |
< |
* @param t the task. Caller must ensure nonnull |
530 |
> |
* Pushes a task. Call only from this thread. |
531 |
> |
* |
532 |
> |
* @param t the task. Caller must ensure non-null. |
533 |
|
*/ |
534 |
|
final void pushTask(ForkJoinTask<?> t) { |
535 |
|
ForkJoinTask<?>[] q = queue; |
536 |
< |
int mask = q.length - 1; |
537 |
< |
int s = sp; |
538 |
< |
_unsafe.putOrderedObject(q, ((s & mask) << qShift) + qBase, t); |
539 |
< |
_unsafe.putOrderedInt(this, spOffset, ++s); |
540 |
< |
if ((s -= base) == 1) |
541 |
< |
pool.signalNonEmptyWorkerQueue(); |
542 |
< |
else if (s >= mask) |
313 |
< |
growQueue(); |
536 |
> |
int mask = q.length - 1; // implicit assert q != null |
537 |
> |
int s = sp++; // ok to increment sp before slot write |
538 |
> |
UNSAFE.putOrderedObject(q, ((s & mask) << qShift) + qBase, t); |
539 |
> |
if ((s -= base) == 0) |
540 |
> |
pool.signalWork(); // was empty |
541 |
> |
else if (s == mask) |
542 |
> |
growQueue(); // is full |
543 |
|
} |
544 |
|
|
545 |
|
/** |
546 |
|
* Tries to take a task from the base of the queue, failing if |
547 |
< |
* either empty or contended. |
548 |
< |
* @return a task, or null if none or contended. |
547 |
> |
* empty or contended. Note: Specializations of this code appear |
548 |
> |
* in locallyDeqTask and elsewhere. |
549 |
> |
* |
550 |
> |
* @return a task, or null if none or contended |
551 |
|
*/ |
552 |
< |
private ForkJoinTask<?> deqTask() { |
322 |
< |
ForkJoinTask<?>[] q; |
552 |
> |
final ForkJoinTask<?> deqTask() { |
553 |
|
ForkJoinTask<?> t; |
554 |
< |
int i; |
555 |
< |
int b; |
554 |
> |
ForkJoinTask<?>[] q; |
555 |
> |
int b, i; |
556 |
|
if (sp != (b = base) && |
557 |
|
(q = queue) != null && // must read q after b |
558 |
< |
(t = q[i = (q.length - 1) & b]) != null && |
559 |
< |
_unsafe.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) { |
558 |
> |
(t = q[i = (q.length - 1) & b]) != null && base == b && |
559 |
> |
UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) { |
560 |
|
base = b + 1; |
561 |
|
return t; |
562 |
|
} |
564 |
|
} |
565 |
|
|
566 |
|
/** |
567 |
< |
* Returns a popped task, or null if empty. Called only by |
568 |
< |
* current thread. |
567 |
> |
* Tries to take a task from the base of own queue. Assumes active |
568 |
> |
* status. Called only by this thread. |
569 |
> |
* |
570 |
> |
* @return a task, or null if none |
571 |
|
*/ |
572 |
< |
final ForkJoinTask<?> popTask() { |
341 |
< |
ForkJoinTask<?> t; |
342 |
< |
int i; |
572 |
> |
final ForkJoinTask<?> locallyDeqTask() { |
573 |
|
ForkJoinTask<?>[] q = queue; |
574 |
< |
int mask = q.length - 1; |
575 |
< |
int s = sp; |
576 |
< |
if (s != base && |
577 |
< |
(t = q[i = (s - 1) & mask]) != null && |
578 |
< |
_unsafe.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) { |
579 |
< |
_unsafe.putOrderedInt(this, spOffset, s - 1); |
580 |
< |
return t; |
574 |
> |
if (q != null) { |
575 |
> |
ForkJoinTask<?> t; |
576 |
> |
int b, i; |
577 |
> |
while (sp != (b = base)) { |
578 |
> |
if ((t = q[i = (q.length - 1) & b]) != null && base == b && |
579 |
> |
UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, |
580 |
> |
t, null)) { |
581 |
> |
base = b + 1; |
582 |
> |
return t; |
583 |
> |
} |
584 |
> |
} |
585 |
> |
} |
586 |
> |
return null; |
587 |
> |
} |
588 |
> |
|
589 |
> |
/** |
590 |
> |
* Returns a popped task, or null if empty. Assumes active status. |
591 |
> |
* Called only by this thread. |
592 |
> |
*/ |
593 |
> |
private ForkJoinTask<?> popTask() { |
594 |
> |
ForkJoinTask<?>[] q = queue; |
595 |
> |
if (q != null) { |
596 |
> |
int s; |
597 |
> |
while ((s = sp) != base) { |
598 |
> |
int i = (q.length - 1) & --s; |
599 |
> |
long u = (i << qShift) + qBase; // raw offset |
600 |
> |
ForkJoinTask<?> t = q[i]; |
601 |
> |
if (t == null) // lost to stealer |
602 |
> |
break; |
603 |
> |
if (UNSAFE.compareAndSwapObject(q, u, t, null)) { |
604 |
> |
sp = s; // putOrderedInt may encourage more timely write |
605 |
> |
// UNSAFE.putOrderedInt(this, spOffset, s); |
606 |
> |
return t; |
607 |
> |
} |
608 |
> |
} |
609 |
|
} |
610 |
|
return null; |
611 |
|
} |
612 |
|
|
613 |
|
/** |
614 |
< |
* Specialized version of popTask to pop only if |
615 |
< |
* topmost element is the given task. Called only |
616 |
< |
* by current thread. |
617 |
< |
* @param t the task. Caller must ensure nonnull |
614 |
> |
* Specialized version of popTask to pop only if topmost element |
615 |
> |
* is the given task. Called only by this thread while active. |
616 |
> |
* |
617 |
> |
* @param t the task. Caller must ensure non-null. |
618 |
|
*/ |
619 |
|
final boolean unpushTask(ForkJoinTask<?> t) { |
620 |
+ |
int s; |
621 |
|
ForkJoinTask<?>[] q = queue; |
622 |
< |
int mask = q.length - 1; |
623 |
< |
int s = sp - 1; |
624 |
< |
if (_unsafe.compareAndSwapObject(q, ((s & mask) << qShift) + qBase, |
625 |
< |
t, null)) { |
626 |
< |
_unsafe.putOrderedInt(this, spOffset, s); |
622 |
> |
if ((s = sp) != base && q != null && |
623 |
> |
UNSAFE.compareAndSwapObject |
624 |
> |
(q, (((q.length - 1) & --s) << qShift) + qBase, t, null)) { |
625 |
> |
sp = s; // putOrderedInt may encourage more timely write |
626 |
> |
// UNSAFE.putOrderedInt(this, spOffset, s); |
627 |
|
return true; |
628 |
|
} |
629 |
|
return false; |
630 |
|
} |
631 |
|
|
632 |
|
/** |
633 |
< |
* Returns next task to pop. |
633 |
> |
* Returns next task, or null if empty or contended. |
634 |
|
*/ |
635 |
|
final ForkJoinTask<?> peekTask() { |
636 |
|
ForkJoinTask<?>[] q = queue; |
637 |
< |
return q == null? null : q[(sp - 1) & (q.length - 1)]; |
637 |
> |
if (q == null) |
638 |
> |
return null; |
639 |
> |
int mask = q.length - 1; |
640 |
> |
int i = locallyFifo ? base : (sp - 1); |
641 |
> |
return q[i & mask]; |
642 |
|
} |
643 |
|
|
644 |
|
/** |
663 |
|
ForkJoinTask<?> t = oldQ[oldIndex]; |
664 |
|
if (t != null && !casSlotNull(oldQ, oldIndex, t)) |
665 |
|
t = null; |
666 |
< |
setSlot(newQ, b & newMask, t); |
666 |
> |
writeSlot(newQ, b & newMask, t); |
667 |
|
} while (++b != bf); |
668 |
< |
pool.signalIdleWorkers(false); |
668 |
> |
pool.signalWork(); |
669 |
|
} |
670 |
|
|
408 |
– |
// Runstate management |
409 |
– |
|
410 |
– |
final boolean isShutdown() { return runState >= SHUTDOWN; } |
411 |
– |
final boolean isTerminating() { return runState >= TERMINATING; } |
412 |
– |
final boolean isTerminated() { return runState == TERMINATED; } |
413 |
– |
final boolean shutdown() { return transitionRunStateTo(SHUTDOWN); } |
414 |
– |
final boolean shutdownNow() { return transitionRunStateTo(TERMINATING); } |
415 |
– |
|
671 |
|
/** |
672 |
< |
* Transition to at least the given state. Return true if not |
673 |
< |
* already at least given state. |
672 |
> |
* Computes next value for random victim probe in scan(). Scans |
673 |
> |
* don't require a very high quality generator, but also not a |
674 |
> |
* crummy one. Marsaglia xor-shift is cheap and works well enough. |
675 |
> |
* Note: This is manually inlined in scan(). |
676 |
|
*/ |
677 |
< |
private boolean transitionRunStateTo(int state) { |
678 |
< |
for (;;) { |
679 |
< |
int s = runState; |
680 |
< |
if (s >= state) |
424 |
< |
return false; |
425 |
< |
if (_unsafe.compareAndSwapInt(this, runStateOffset, s, state)) |
426 |
< |
return true; |
427 |
< |
} |
677 |
> |
private static final int xorShift(int r) { |
678 |
> |
r ^= r << 13; |
679 |
> |
r ^= r >>> 17; |
680 |
> |
return r ^ (r << 5); |
681 |
|
} |
682 |
|
|
683 |
|
/** |
684 |
< |
* Ensure status is active and if necessary adjust pool active count |
684 |
> |
* Tries to steal a task from another worker. Starts at a random |
685 |
> |
* index of workers array, and probes workers until finding one |
686 |
> |
* with non-empty queue or finding that all are empty. It |
687 |
> |
* randomly selects the first n probes. If these are empty, it |
688 |
> |
* resorts to a circular sweep, which is necessary to accurately |
689 |
> |
* set active status. (The circular sweep uses steps of |
690 |
> |
* approximately half the array size plus 1, to avoid bias |
691 |
> |
* stemming from leftmost packing of the array in ForkJoinPool.) |
692 |
> |
* |
693 |
> |
* This method must be both fast and quiet -- usually avoiding |
694 |
> |
* memory accesses that could disrupt cache sharing etc other than |
695 |
> |
* those needed to check for and take tasks (or to activate if not |
696 |
> |
* already active). This accounts for, among other things, |
697 |
> |
* updating random seed in place without storing it until exit. |
698 |
> |
* |
699 |
> |
* @return a task, or null if none found |
700 |
|
*/ |
701 |
< |
final void activate() { |
702 |
< |
if (!active) { |
703 |
< |
active = true; |
704 |
< |
pool.incrementActiveCount(); |
701 |
> |
private ForkJoinTask<?> scan() { |
702 |
> |
ForkJoinPool p = pool; |
703 |
> |
ForkJoinWorkerThread[] ws; // worker array |
704 |
> |
int n; // upper bound of #workers |
705 |
> |
if ((ws = p.workers) != null && (n = ws.length) > 1) { |
706 |
> |
boolean canSteal = active; // shadow active status |
707 |
> |
int r = seed; // extract seed once |
708 |
> |
int mask = n - 1; |
709 |
> |
int j = -n; // loop counter |
710 |
> |
int k = r; // worker index, random if j < 0 |
711 |
> |
for (;;) { |
712 |
> |
ForkJoinWorkerThread v = ws[k & mask]; |
713 |
> |
r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // inline xorshift |
714 |
> |
ForkJoinTask<?>[] q; ForkJoinTask<?> t; int b, a; |
715 |
> |
if (v != null && (b = v.base) != v.sp && |
716 |
> |
(q = v.queue) != null) { |
717 |
> |
int i = (q.length - 1) & b; |
718 |
> |
long u = (i << qShift) + qBase; // raw offset |
719 |
> |
int pid = poolIndex; |
720 |
> |
if ((t = q[i]) != null) { |
721 |
> |
if (!canSteal && // inline p.tryIncrementActiveCount |
722 |
> |
UNSAFE.compareAndSwapInt(p, poolRunStateOffset, |
723 |
> |
a = p.runState, a + 1)) |
724 |
> |
canSteal = active = true; |
725 |
> |
if (canSteal && v.base == b++ && |
726 |
> |
UNSAFE.compareAndSwapObject(q, u, t, null)) { |
727 |
> |
v.base = b; |
728 |
> |
v.stealHint = pid; |
729 |
> |
UNSAFE.putOrderedObject(this, |
730 |
> |
currentStealOffset, t); |
731 |
> |
seed = r; |
732 |
> |
++stealCount; |
733 |
> |
return t; |
734 |
> |
} |
735 |
> |
} |
736 |
> |
j = -n; |
737 |
> |
k = r; // restart on contention |
738 |
> |
} |
739 |
> |
else if (++j <= 0) |
740 |
> |
k = r; |
741 |
> |
else if (j <= n) |
742 |
> |
k += (n >>> 1) | 1; |
743 |
> |
else |
744 |
> |
break; |
745 |
> |
} |
746 |
|
} |
747 |
+ |
return null; |
748 |
|
} |
749 |
|
|
750 |
+ |
// Run State management |
751 |
+ |
|
752 |
+ |
// status check methods used mainly by ForkJoinPool |
753 |
+ |
final boolean isRunning() { return runState == 0; } |
754 |
+ |
final boolean isTerminating() { return (runState & TERMINATING) != 0; } |
755 |
+ |
final boolean isTerminated() { return (runState & TERMINATED) != 0; } |
756 |
+ |
final boolean isSuspended() { return (runState & SUSPENDED) != 0; } |
757 |
+ |
final boolean isTrimmed() { return (runState & TRIMMED) != 0; } |
758 |
+ |
|
759 |
|
/** |
760 |
< |
* Ensure status is inactive and if necessary adjust pool active count |
760 |
> |
* Sets state to TERMINATING. Does NOT unpark or interrupt |
761 |
> |
* to wake up if currently blocked. Callers must do so if desired. |
762 |
|
*/ |
763 |
< |
final void inactivate() { |
764 |
< |
if (active) { |
765 |
< |
active = false; |
766 |
< |
pool.decrementActiveCount(); |
763 |
> |
final void shutdown() { |
764 |
> |
for (;;) { |
765 |
> |
int s = runState; |
766 |
> |
if ((s & (TERMINATING|TERMINATED)) != 0) |
767 |
> |
break; |
768 |
> |
if ((s & SUSPENDED) != 0) { // kill and wakeup if suspended |
769 |
> |
if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, |
770 |
> |
(s & ~SUSPENDED) | |
771 |
> |
(TRIMMED|TERMINATING))) |
772 |
> |
break; |
773 |
> |
} |
774 |
> |
else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, |
775 |
> |
s | TERMINATING)) |
776 |
> |
break; |
777 |
|
} |
778 |
|
} |
779 |
|
|
450 |
– |
// Lifecycle methods |
451 |
– |
|
780 |
|
/** |
781 |
< |
* Initializes internal state after construction but before |
454 |
< |
* processing any tasks. If you override this method, you must |
455 |
< |
* invoke super.onStart() at the beginning of the method. |
456 |
< |
* Initialization requires care: Most fields must have legal |
457 |
< |
* default values, to ensure that attempted accesses from other |
458 |
< |
* threads work correctly even before this thread starts |
459 |
< |
* processing tasks. |
781 |
> |
* Sets state to TERMINATED. Called only by onTermination(). |
782 |
|
*/ |
783 |
< |
protected void onStart() { |
784 |
< |
juRandomSeed = randomSeedGenerator.nextLong(); |
785 |
< |
do;while((randomVictimSeed = nextRandomInt()) == 0); // must be nonzero |
786 |
< |
if (queue == null) |
787 |
< |
queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY]; |
466 |
< |
|
467 |
< |
// Heuristically allow one initial thread to warm up; others wait |
468 |
< |
if (poolIndex < pool.getParallelism() - 1) { |
469 |
< |
eventCount = pool.sync(this, 0); |
470 |
< |
activate(); |
471 |
< |
} |
783 |
> |
private void setTerminated() { |
784 |
> |
int s; |
785 |
> |
do {} while (!UNSAFE.compareAndSwapInt(this, runStateOffset, |
786 |
> |
s = runState, |
787 |
> |
s | (TERMINATING|TERMINATED))); |
788 |
|
} |
789 |
|
|
790 |
|
/** |
791 |
< |
* Perform cleanup associated with termination of this worker |
792 |
< |
* thread. If you override this method, you must invoke |
477 |
< |
* super.onTermination at the end of the overridden method. |
791 |
> |
* If suspended, tries to set status to unsuspended. |
792 |
> |
* Does NOT wake up if blocked. |
793 |
|
* |
794 |
< |
* @param exception the exception causing this thread to abort due |
480 |
< |
* to an unrecoverable error, or null if completed normally. |
794 |
> |
* @return true if successful |
795 |
|
*/ |
796 |
< |
protected void onTermination(Throwable exception) { |
797 |
< |
try { |
798 |
< |
clearLocalTasks(); |
799 |
< |
inactivate(); |
800 |
< |
cancelTasks(); |
801 |
< |
} finally { |
488 |
< |
terminate(exception); |
796 |
> |
final boolean tryUnsuspend() { |
797 |
> |
int s; |
798 |
> |
while (((s = runState) & SUSPENDED) != 0) { |
799 |
> |
if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, |
800 |
> |
s & ~SUSPENDED)) |
801 |
> |
return true; |
802 |
|
} |
803 |
+ |
return false; |
804 |
|
} |
805 |
|
|
806 |
|
/** |
807 |
< |
* Notify pool of termination and, if exception is nonnull, |
808 |
< |
* rethrow it to trigger this thread's uncaughtExceptionHandler |
807 |
> |
* Sets suspended status and blocks as spare until resumed |
808 |
> |
* or shutdown. |
809 |
|
*/ |
810 |
< |
private void terminate(Throwable exception) { |
811 |
< |
transitionRunStateTo(TERMINATED); |
812 |
< |
try { |
813 |
< |
pool.workerTerminated(this); |
814 |
< |
} finally { |
815 |
< |
if (exception != null) |
816 |
< |
ForkJoinTask.rethrowException(exception); |
810 |
> |
final void suspendAsSpare() { |
811 |
> |
for (;;) { // set suspended unless terminating |
812 |
> |
int s = runState; |
813 |
> |
if ((s & TERMINATING) != 0) { // must kill |
814 |
> |
if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, |
815 |
> |
s | (TRIMMED | TERMINATING))) |
816 |
> |
return; |
817 |
> |
} |
818 |
> |
else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, |
819 |
> |
s | SUSPENDED)) |
820 |
> |
break; |
821 |
> |
} |
822 |
> |
ForkJoinPool p = pool; |
823 |
> |
p.pushSpare(this); |
824 |
> |
while ((runState & SUSPENDED) != 0) { |
825 |
> |
if (p.tryAccumulateStealCount(this)) { |
826 |
> |
interrupted(); // clear/ignore interrupts |
827 |
> |
if ((runState & SUSPENDED) == 0) |
828 |
> |
break; |
829 |
> |
LockSupport.park(this); |
830 |
> |
} |
831 |
|
} |
832 |
|
} |
833 |
|
|
834 |
+ |
// Misc support methods for ForkJoinPool |
835 |
+ |
|
836 |
|
/** |
837 |
< |
* Run local tasks on exit from main. |
837 |
> |
* Returns an estimate of the number of tasks in the queue. Also |
838 |
> |
* used by ForkJoinTask. |
839 |
|
*/ |
840 |
< |
private void clearLocalTasks() { |
841 |
< |
while (base != sp && !pool.isTerminating()) { |
842 |
< |
ForkJoinTask<?> t = popTask(); |
512 |
< |
if (t != null) { |
513 |
< |
activate(); // ensure active status |
514 |
< |
t.quietlyExec(); |
515 |
< |
} |
516 |
< |
} |
840 |
> |
final int getQueueSize() { |
841 |
> |
int n; // external calls must read base first |
842 |
> |
return (n = -base + sp) <= 0 ? 0 : n; |
843 |
|
} |
844 |
|
|
845 |
|
/** |
847 |
|
* thread. |
848 |
|
*/ |
849 |
|
final void cancelTasks() { |
850 |
+ |
ForkJoinTask<?> cj = currentJoin; // try to cancel ongoing tasks |
851 |
+ |
if (cj != null) { |
852 |
+ |
currentJoin = null; |
853 |
+ |
cj.cancelIgnoringExceptions(); |
854 |
+ |
try { |
855 |
+ |
this.interrupt(); // awaken wait |
856 |
+ |
} catch (SecurityException ignore) { |
857 |
+ |
} |
858 |
+ |
} |
859 |
+ |
ForkJoinTask<?> cs = currentSteal; |
860 |
+ |
if (cs != null) { |
861 |
+ |
currentSteal = null; |
862 |
+ |
cs.cancelIgnoringExceptions(); |
863 |
+ |
} |
864 |
|
while (base != sp) { |
865 |
|
ForkJoinTask<?> t = deqTask(); |
866 |
|
if (t != null) |
869 |
|
} |
870 |
|
|
871 |
|
/** |
872 |
< |
* This method is required to be public, but should never be |
873 |
< |
* called explicitly. It performs the main run loop to execute |
874 |
< |
* ForkJoinTasks. |
872 |
> |
* Drains tasks to given collection c. |
873 |
> |
* |
874 |
> |
* @return the number of tasks drained |
875 |
|
*/ |
876 |
< |
public void run() { |
877 |
< |
Throwable exception = null; |
878 |
< |
try { |
879 |
< |
onStart(); |
880 |
< |
while (!isShutdown()) |
881 |
< |
step(); |
882 |
< |
} catch (Throwable ex) { |
883 |
< |
exception = ex; |
544 |
< |
} finally { |
545 |
< |
onTermination(exception); |
876 |
> |
final int drainTasksTo(Collection<? super ForkJoinTask<?>> c) { |
877 |
> |
int n = 0; |
878 |
> |
while (base != sp) { |
879 |
> |
ForkJoinTask<?> t = deqTask(); |
880 |
> |
if (t != null) { |
881 |
> |
c.add(t); |
882 |
> |
++n; |
883 |
> |
} |
884 |
|
} |
885 |
+ |
return n; |
886 |
|
} |
887 |
|
|
888 |
+ |
// Support methods for ForkJoinTask |
889 |
+ |
|
890 |
|
/** |
891 |
< |
* Main top-level action. |
891 |
> |
* Gets and removes a local task. |
892 |
> |
* |
893 |
> |
* @return a task, if available |
894 |
|
*/ |
895 |
< |
private void step() { |
896 |
< |
ForkJoinTask<?> t = sp != base? popTask() : null; |
897 |
< |
if (t != null || (t = scan(null, true)) != null) { |
898 |
< |
activate(); |
899 |
< |
t.quietlyExec(); |
895 |
> |
final ForkJoinTask<?> pollLocalTask() { |
896 |
> |
ForkJoinPool p = pool; |
897 |
> |
while (sp != base) { |
898 |
> |
int a; // inline p.tryIncrementActiveCount |
899 |
> |
if (active || |
900 |
> |
(active = UNSAFE.compareAndSwapInt(p, poolRunStateOffset, |
901 |
> |
a = p.runState, a + 1))) |
902 |
> |
return locallyFifo ? locallyDeqTask() : popTask(); |
903 |
|
} |
904 |
< |
else { |
905 |
< |
inactivate(); |
906 |
< |
eventCount = pool.sync(this, eventCount); |
904 |
> |
return null; |
905 |
> |
} |
906 |
> |
|
907 |
> |
/** |
908 |
> |
* Gets and removes a local or stolen task. |
909 |
> |
* |
910 |
> |
* @return a task, if available |
911 |
> |
*/ |
912 |
> |
final ForkJoinTask<?> pollTask() { |
913 |
> |
ForkJoinTask<?> t = pollLocalTask(); |
914 |
> |
if (t == null) { |
915 |
> |
t = scan(); |
916 |
> |
// cannot retain/track/help steal |
917 |
> |
UNSAFE.putOrderedObject(this, currentStealOffset, null); |
918 |
|
} |
919 |
+ |
return t; |
920 |
|
} |
921 |
|
|
922 |
< |
// scanning for and stealing tasks |
922 |
> |
/** |
923 |
> |
* Possibly runs some tasks and/or blocks, until task is done. |
924 |
> |
* |
925 |
> |
* @param joinMe the task to join |
926 |
> |
*/ |
927 |
> |
final void joinTask(ForkJoinTask<?> joinMe) { |
928 |
> |
// currentJoin only written by this thread; only need ordered store |
929 |
> |
ForkJoinTask<?> prevJoin = currentJoin; |
930 |
> |
UNSAFE.putOrderedObject(this, currentJoinOffset, joinMe); |
931 |
> |
if (sp != base) |
932 |
> |
localHelpJoinTask(joinMe); |
933 |
> |
if (joinMe.status >= 0) |
934 |
> |
pool.awaitJoin(joinMe, this); |
935 |
> |
UNSAFE.putOrderedObject(this, currentJoinOffset, prevJoin); |
936 |
> |
} |
937 |
|
|
938 |
|
/** |
939 |
< |
* Computes next value for random victim probe. Scans don't |
568 |
< |
* require a very high quality generator, but also not a crummy |
569 |
< |
* one. Marsaglia xor-shift is cheap and works well. |
939 |
> |
* Run tasks in local queue until given task is done. |
940 |
|
* |
941 |
< |
* This is currently unused, and manually inlined |
941 |
> |
* @param joinMe the task to join |
942 |
|
*/ |
943 |
< |
private static int xorShift(int r) { |
944 |
< |
r ^= r << 1; |
945 |
< |
r ^= r >>> 3; |
946 |
< |
r ^= r << 10; |
947 |
< |
return r; |
943 |
> |
private void localHelpJoinTask(ForkJoinTask<?> joinMe) { |
944 |
> |
int s; |
945 |
> |
ForkJoinTask<?>[] q; |
946 |
> |
while (joinMe.status >= 0 && (s = sp) != base && (q = queue) != null) { |
947 |
> |
int i = (q.length - 1) & --s; |
948 |
> |
long u = (i << qShift) + qBase; // raw offset |
949 |
> |
ForkJoinTask<?> t = q[i]; |
950 |
> |
if (t == null) // lost to a stealer |
951 |
> |
break; |
952 |
> |
if (UNSAFE.compareAndSwapObject(q, u, t, null)) { |
953 |
> |
/* |
954 |
> |
* This recheck (and similarly in helpJoinTask) |
955 |
> |
* handles cases where joinMe is independently |
956 |
> |
* cancelled or forced even though there is other work |
957 |
> |
* available. Back out of the pop by putting t back |
958 |
> |
* into slot before we commit by writing sp. |
959 |
> |
*/ |
960 |
> |
if (joinMe.status < 0) { |
961 |
> |
UNSAFE.putObjectVolatile(q, u, t); |
962 |
> |
break; |
963 |
> |
} |
964 |
> |
sp = s; |
965 |
> |
// UNSAFE.putOrderedInt(this, spOffset, s); |
966 |
> |
t.quietlyExec(); |
967 |
> |
} |
968 |
> |
} |
969 |
|
} |
970 |
|
|
971 |
|
/** |
972 |
< |
* Tries to steal a task from another worker and/or, if enabled, |
973 |
< |
* submission queue. Starts at a random index of workers array, |
974 |
< |
* and probes workers until finding one with non-empty queue or |
975 |
< |
* finding that all are empty. It randomly selects the first n-1 |
976 |
< |
* probes. If these are empty, it resorts to full circular |
586 |
< |
* traversal, which is necessary to accurately set active status |
587 |
< |
* by caller. Also restarts if pool barrier has tripped since last |
588 |
< |
* scan, which forces refresh of workers array, in case barrier |
589 |
< |
* was associated with resize. |
972 |
> |
* Unless terminating, tries to locate and help perform tasks for |
973 |
> |
* a stealer of the given task, or in turn one of its stealers. |
974 |
> |
* Traces currentSteal->currentJoin links looking for a thread |
975 |
> |
* working on a descendant of the given task and with a non-empty |
976 |
> |
* queue to steal back and execute tasks from. |
977 |
|
* |
978 |
< |
* This method must be both fast and quiet -- usually avoiding |
979 |
< |
* memory accesses that could disrupt cache sharing etc other than |
980 |
< |
* those needed to check for and take tasks. This accounts for, |
981 |
< |
* among other things, updating random seed in place without |
982 |
< |
* storing it until exit. (Note that we only need to store it if |
983 |
< |
* we found a task; otherwise it doesn't matter if we start at the |
597 |
< |
* same place next time.) |
978 |
> |
* The implementation is very branchy to cope with potential |
979 |
> |
* inconsistencies or loops encountering chains that are stale, |
980 |
> |
* unknown, or of length greater than MAX_HELP_DEPTH links. All |
981 |
> |
* of these cases are dealt with by just returning back to the |
982 |
> |
* caller, who is expected to retry if other join mechanisms also |
983 |
> |
* don't work out. |
984 |
|
* |
985 |
< |
* @param joinMe if non null; exit early if done |
600 |
< |
* @param checkSubmissions true if OK to take submissions |
601 |
< |
* @return a task, or null if none found |
985 |
> |
* @param joinMe the task to join |
986 |
|
*/ |
987 |
< |
private ForkJoinTask<?> scan(ForkJoinTask<?> joinMe, |
988 |
< |
boolean checkSubmissions) { |
989 |
< |
ForkJoinPool p = pool; |
990 |
< |
if (p == null) // Never null, but avoids |
991 |
< |
return null; // implicit nullchecks below |
992 |
< |
int r = randomVictimSeed; // extract once to keep scan quiet |
993 |
< |
restart: // outer loop refreshes ws array |
994 |
< |
while (joinMe == null || joinMe.status >= 0) { |
995 |
< |
int mask; |
996 |
< |
ForkJoinWorkerThread[] ws = p.workers; |
997 |
< |
if (ws != null && (mask = ws.length - 1) > 0) { |
998 |
< |
int probes = -mask; // use random index while negative |
999 |
< |
int idx = r; |
1000 |
< |
for (;;) { |
1001 |
< |
ForkJoinWorkerThread v; |
1002 |
< |
// inlined xorshift to update seed |
1003 |
< |
r ^= r << 1; r ^= r >>> 3; r ^= r << 10; |
1004 |
< |
if ((v = ws[mask & idx]) != null && v.sp != v.base) { |
1005 |
< |
ForkJoinTask<?> t; |
1006 |
< |
activate(); |
1007 |
< |
if ((joinMe == null || joinMe.status >= 0) && |
1008 |
< |
(t = v.deqTask()) != null) { |
1009 |
< |
randomVictimSeed = r; |
1010 |
< |
++stealCount; |
1011 |
< |
return t; |
987 |
> |
final void helpJoinTask(ForkJoinTask<?> joinMe) { |
988 |
> |
ForkJoinWorkerThread[] ws; |
989 |
> |
int n; |
990 |
> |
if (joinMe.status < 0) // already done |
991 |
> |
return; |
992 |
> |
if ((runState & TERMINATING) != 0) { // cancel if shutting down |
993 |
> |
joinMe.cancelIgnoringExceptions(); |
994 |
> |
return; |
995 |
> |
} |
996 |
> |
if ((ws = pool.workers) == null || (n = ws.length) <= 1) |
997 |
> |
return; // need at least 2 workers |
998 |
> |
|
999 |
> |
ForkJoinTask<?> task = joinMe; // base of chain |
1000 |
> |
ForkJoinWorkerThread thread = this; // thread with stolen task |
1001 |
> |
for (int d = 0; d < MAX_HELP_DEPTH; ++d) { // chain length |
1002 |
> |
// Try to find v, the stealer of task, by first using hint |
1003 |
> |
ForkJoinWorkerThread v = ws[thread.stealHint & (n - 1)]; |
1004 |
> |
if (v == null || v.currentSteal != task) { |
1005 |
> |
for (int j = 0; ; ++j) { // search array |
1006 |
> |
if (j < n) { |
1007 |
> |
ForkJoinTask<?> vs; |
1008 |
> |
if ((v = ws[j]) != null && |
1009 |
> |
(vs = v.currentSteal) != null) { |
1010 |
> |
if (joinMe.status < 0 || task.status < 0) |
1011 |
> |
return; // stale or done |
1012 |
> |
if (vs == task) { |
1013 |
> |
thread.stealHint = j; |
1014 |
> |
break; // save hint for next time |
1015 |
> |
} |
1016 |
|
} |
629 |
– |
continue restart; // restart on contention |
1017 |
|
} |
631 |
– |
if ((probes >> 1) <= mask) // n-1 random then circular |
632 |
– |
idx = (probes++ < 0)? r : (idx + 1); |
1018 |
|
else |
1019 |
< |
break; |
1019 |
> |
return; // no stealer |
1020 |
|
} |
1021 |
|
} |
1022 |
< |
if (checkSubmissions && p.hasQueuedSubmissions()) { |
1023 |
< |
activate(); |
1024 |
< |
ForkJoinTask<?> t = p.pollSubmission(); |
1025 |
< |
if (t != null) |
1026 |
< |
return t; |
1027 |
< |
} |
643 |
< |
else { |
644 |
< |
long ec = eventCount; // restart on pool event |
645 |
< |
if ((eventCount = p.getEventCount()) == ec) |
1022 |
> |
for (;;) { // Try to help v, using specialized form of deqTask |
1023 |
> |
if (joinMe.status < 0) |
1024 |
> |
return; |
1025 |
> |
int b = v.base; |
1026 |
> |
ForkJoinTask<?>[] q = v.queue; |
1027 |
> |
if (b == v.sp || q == null) |
1028 |
|
break; |
1029 |
+ |
int i = (q.length - 1) & b; |
1030 |
+ |
long u = (i << qShift) + qBase; |
1031 |
+ |
ForkJoinTask<?> t = q[i]; |
1032 |
+ |
int pid = poolIndex; |
1033 |
+ |
ForkJoinTask<?> ps = currentSteal; |
1034 |
+ |
if (task.status < 0) |
1035 |
+ |
return; // stale or done |
1036 |
+ |
if (t != null && v.base == b++ && |
1037 |
+ |
UNSAFE.compareAndSwapObject(q, u, t, null)) { |
1038 |
+ |
if (joinMe.status < 0) { |
1039 |
+ |
UNSAFE.putObjectVolatile(q, u, t); |
1040 |
+ |
return; // back out on cancel |
1041 |
+ |
} |
1042 |
+ |
v.base = b; |
1043 |
+ |
v.stealHint = pid; |
1044 |
+ |
UNSAFE.putOrderedObject(this, currentStealOffset, t); |
1045 |
+ |
t.quietlyExec(); |
1046 |
+ |
UNSAFE.putOrderedObject(this, currentStealOffset, ps); |
1047 |
+ |
} |
1048 |
|
} |
1049 |
< |
} |
1050 |
< |
return null; |
1051 |
< |
} |
1052 |
< |
|
1053 |
< |
/** |
1054 |
< |
* Callback from pool.sync to rescan before blocking. If a |
1055 |
< |
* task is found, it is pushed so it can be executed upon return. |
655 |
< |
* @return true if found and pushed a task |
656 |
< |
*/ |
657 |
< |
final boolean prescan() { |
658 |
< |
ForkJoinTask<?> t = scan(null, true); |
659 |
< |
if (t != null) { |
660 |
< |
pushTask(t); |
661 |
< |
return true; |
662 |
< |
} |
663 |
< |
else { |
664 |
< |
inactivate(); |
665 |
< |
return false; |
1049 |
> |
// Try to descend to find v's stealer |
1050 |
> |
ForkJoinTask<?> next = v.currentJoin; |
1051 |
> |
if (task.status < 0 || next == null || next == task || |
1052 |
> |
joinMe.status < 0) |
1053 |
> |
return; |
1054 |
> |
task = next; |
1055 |
> |
thread = v; |
1056 |
|
} |
1057 |
|
} |
1058 |
|
|
669 |
– |
// Support for ForkJoinTask methods |
670 |
– |
|
1059 |
|
/** |
1060 |
< |
* Scan, returning early if joinMe done |
1061 |
< |
*/ |
1062 |
< |
final ForkJoinTask<?> scanWhileJoining(ForkJoinTask<?> joinMe) { |
1063 |
< |
ForkJoinTask<?> t = scan(joinMe, false); |
1064 |
< |
if (t != null && joinMe.status < 0 && sp == base) { |
1065 |
< |
pushTask(t); // unsteal if done and this task would be stealable |
1066 |
< |
t = null; |
1067 |
< |
} |
1068 |
< |
return t; |
1069 |
< |
} |
1070 |
< |
|
1071 |
< |
/** |
1072 |
< |
* Pops or steals a task |
1073 |
< |
* @return task, or null if none available |
1060 |
> |
* Implements ForJoinTask.getSurplusQueuedTaskCount(). |
1061 |
> |
* Returns an estimate of the number of tasks, offset by a |
1062 |
> |
* function of number of idle workers. |
1063 |
> |
* |
1064 |
> |
* This method provides a cheap heuristic guide for task |
1065 |
> |
* partitioning when programmers, frameworks, tools, or languages |
1066 |
> |
* have little or no idea about task granularity. In essence by |
1067 |
> |
* offering this method, we ask users only about tradeoffs in |
1068 |
> |
* overhead vs expected throughput and its variance, rather than |
1069 |
> |
* how finely to partition tasks. |
1070 |
> |
* |
1071 |
> |
* In a steady state strict (tree-structured) computation, each |
1072 |
> |
* thread makes available for stealing enough tasks for other |
1073 |
> |
* threads to remain active. Inductively, if all threads play by |
1074 |
> |
* the same rules, each thread should make available only a |
1075 |
> |
* constant number of tasks. |
1076 |
> |
* |
1077 |
> |
* The minimum useful constant is just 1. But using a value of 1 |
1078 |
> |
* would require immediate replenishment upon each steal to |
1079 |
> |
* maintain enough tasks, which is infeasible. Further, |
1080 |
> |
* partitionings/granularities of offered tasks should minimize |
1081 |
> |
* steal rates, which in general means that threads nearer the top |
1082 |
> |
* of computation tree should generate more than those nearer the |
1083 |
> |
* bottom. In perfect steady state, each thread is at |
1084 |
> |
* approximately the same level of computation tree. However, |
1085 |
> |
* producing extra tasks amortizes the uncertainty of progress and |
1086 |
> |
* diffusion assumptions. |
1087 |
> |
* |
1088 |
> |
* So, users will want to use values larger, but not much larger |
1089 |
> |
* than 1 to both smooth over transient shortages and hedge |
1090 |
> |
* against uneven progress; as traded off against the cost of |
1091 |
> |
* extra task overhead. We leave the user to pick a threshold |
1092 |
> |
* value to compare with the results of this call to guide |
1093 |
> |
* decisions, but recommend values such as 3. |
1094 |
> |
* |
1095 |
> |
* When all threads are active, it is on average OK to estimate |
1096 |
> |
* surplus strictly locally. In steady-state, if one thread is |
1097 |
> |
* maintaining say 2 surplus tasks, then so are others. So we can |
1098 |
> |
* just use estimated queue length (although note that (sp - base) |
1099 |
> |
* can be an overestimate because of stealers lagging increments |
1100 |
> |
* of base). However, this strategy alone leads to serious |
1101 |
> |
* mis-estimates in some non-steady-state conditions (ramp-up, |
1102 |
> |
* ramp-down, other stalls). We can detect many of these by |
1103 |
> |
* further considering the number of "idle" threads, that are |
1104 |
> |
* known to have zero queued tasks, so compensate by a factor of |
1105 |
> |
* (#idle/#active) threads. |
1106 |
|
*/ |
1107 |
< |
final ForkJoinTask<?> pollLocalOrStolenTask() { |
1108 |
< |
ForkJoinTask<?> t; |
689 |
< |
return (t = popTask()) == null? scan(null, false) : t; |
1107 |
> |
final int getEstimatedSurplusTaskCount() { |
1108 |
> |
return sp - base - pool.idlePerActive(); |
1109 |
|
} |
1110 |
|
|
1111 |
|
/** |
1112 |
< |
* Runs tasks until pool isQuiescent |
1112 |
> |
* Runs tasks until {@code pool.isQuiescent()}. |
1113 |
|
*/ |
1114 |
|
final void helpQuiescePool() { |
1115 |
+ |
ForkJoinTask<?> ps = currentSteal; // to restore below |
1116 |
|
for (;;) { |
1117 |
< |
ForkJoinTask<?> t = pollLocalOrStolenTask(); |
1118 |
< |
if (t != null) { |
699 |
< |
activate(); |
1117 |
> |
ForkJoinTask<?> t = pollLocalTask(); |
1118 |
> |
if (t != null || (t = scan()) != null) |
1119 |
|
t.quietlyExec(); |
701 |
– |
} |
1120 |
|
else { |
1121 |
< |
inactivate(); |
1122 |
< |
if (pool.isQuiescent()) { |
1123 |
< |
activate(); // re-activate on exit |
1124 |
< |
break; |
1121 |
> |
ForkJoinPool p = pool; |
1122 |
> |
int a; // to inline CASes |
1123 |
> |
if (active) { |
1124 |
> |
if (!UNSAFE.compareAndSwapInt |
1125 |
> |
(p, poolRunStateOffset, a = p.runState, a - 1)) |
1126 |
> |
continue; // retry later |
1127 |
> |
active = false; // inactivate |
1128 |
> |
UNSAFE.putOrderedObject(this, currentStealOffset, ps); |
1129 |
> |
} |
1130 |
> |
if (p.isQuiescent()) { |
1131 |
> |
active = true; // re-activate |
1132 |
> |
do {} while (!UNSAFE.compareAndSwapInt |
1133 |
> |
(p, poolRunStateOffset, a = p.runState, a+1)); |
1134 |
> |
return; |
1135 |
|
} |
1136 |
|
} |
1137 |
|
} |
1138 |
|
} |
1139 |
|
|
1140 |
< |
/** |
713 |
< |
* Returns an estimate of the number of tasks in the queue. |
714 |
< |
*/ |
715 |
< |
final int getQueueSize() { |
716 |
< |
int n = sp - base; |
717 |
< |
return n <= 0? 0 : n; // suppress momentarily negative values |
718 |
< |
} |
719 |
< |
|
720 |
< |
/** |
721 |
< |
* Returns an estimate of the number of tasks, offset by a |
722 |
< |
* function of number of idle workers. |
723 |
< |
*/ |
724 |
< |
final int getEstimatedSurplusTaskCount() { |
725 |
< |
// The halving approximates weighting idle vs non-idle workers |
726 |
< |
return (sp - base) - (pool.getIdleThreadCount() >>> 1); |
727 |
< |
} |
728 |
< |
|
729 |
< |
// Per-worker exported random numbers |
1140 |
> |
// Unsafe mechanics |
1141 |
|
|
1142 |
< |
// Same constants as java.util.Random |
1143 |
< |
final static long JURandomMultiplier = 0x5DEECE66DL; |
1144 |
< |
final static long JURandomAddend = 0xBL; |
1145 |
< |
final static long JURandomMask = (1L << 48) - 1; |
1146 |
< |
|
1147 |
< |
private final int nextJURandom(int bits) { |
1148 |
< |
long next = (juRandomSeed * JURandomMultiplier + JURandomAddend) & |
1149 |
< |
JURandomMask; |
1150 |
< |
juRandomSeed = next; |
1151 |
< |
return (int)(next >>> (48 - bits)); |
1152 |
< |
} |
1153 |
< |
|
1154 |
< |
private final int nextJURandomInt(int n) { |
744 |
< |
if (n <= 0) |
745 |
< |
throw new IllegalArgumentException("n must be positive"); |
746 |
< |
int bits = nextJURandom(31); |
747 |
< |
if ((n & -n) == n) |
748 |
< |
return (int)((n * (long)bits) >> 31); |
1142 |
> |
private static final sun.misc.Unsafe UNSAFE = getUnsafe(); |
1143 |
> |
private static final long spOffset = |
1144 |
> |
objectFieldOffset("sp", ForkJoinWorkerThread.class); |
1145 |
> |
private static final long runStateOffset = |
1146 |
> |
objectFieldOffset("runState", ForkJoinWorkerThread.class); |
1147 |
> |
private static final long currentJoinOffset = |
1148 |
> |
objectFieldOffset("currentJoin", ForkJoinWorkerThread.class); |
1149 |
> |
private static final long currentStealOffset = |
1150 |
> |
objectFieldOffset("currentSteal", ForkJoinWorkerThread.class); |
1151 |
> |
private static final long qBase = |
1152 |
> |
UNSAFE.arrayBaseOffset(ForkJoinTask[].class); |
1153 |
> |
private static final long poolRunStateOffset = // to inline CAS |
1154 |
> |
objectFieldOffset("runState", ForkJoinPool.class); |
1155 |
|
|
1156 |
< |
for (;;) { |
751 |
< |
int val = bits % n; |
752 |
< |
if (bits - val + (n-1) >= 0) |
753 |
< |
return val; |
754 |
< |
bits = nextJURandom(31); |
755 |
< |
} |
756 |
< |
} |
1156 |
> |
private static final int qShift; |
1157 |
|
|
1158 |
< |
private final long nextJURandomLong() { |
1159 |
< |
return ((long)(nextJURandom(32)) << 32) + nextJURandom(32); |
1158 |
> |
static { |
1159 |
> |
int s = UNSAFE.arrayIndexScale(ForkJoinTask[].class); |
1160 |
> |
if ((s & (s-1)) != 0) |
1161 |
> |
throw new Error("data type scale not a power of two"); |
1162 |
> |
qShift = 31 - Integer.numberOfLeadingZeros(s); |
1163 |
> |
MAXIMUM_QUEUE_CAPACITY = 1 << (31 - qShift); |
1164 |
|
} |
1165 |
|
|
1166 |
< |
private final long nextJURandomLong(long n) { |
1167 |
< |
if (n <= 0) |
1168 |
< |
throw new IllegalArgumentException("n must be positive"); |
1169 |
< |
long offset = 0; |
1170 |
< |
while (n >= Integer.MAX_VALUE) { // randomly pick half range |
1171 |
< |
int bits = nextJURandom(2); // 2nd bit for odd vs even split |
1172 |
< |
long half = n >>> 1; |
1173 |
< |
long nextn = ((bits & 2) == 0)? half : n - half; |
770 |
< |
if ((bits & 1) == 0) |
771 |
< |
offset += n - nextn; |
772 |
< |
n = nextn; |
1166 |
> |
private static long objectFieldOffset(String field, Class<?> klazz) { |
1167 |
> |
try { |
1168 |
> |
return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field)); |
1169 |
> |
} catch (NoSuchFieldException e) { |
1170 |
> |
// Convert Exception to corresponding Error |
1171 |
> |
NoSuchFieldError error = new NoSuchFieldError(field); |
1172 |
> |
error.initCause(e); |
1173 |
> |
throw error; |
1174 |
|
} |
774 |
– |
return offset + nextJURandomInt((int)n); |
775 |
– |
} |
776 |
– |
|
777 |
– |
private final double nextJURandomDouble() { |
778 |
– |
return (((long)(nextJURandom(26)) << 27) + nextJURandom(27)) |
779 |
– |
/ (double)(1L << 53); |
1175 |
|
} |
1176 |
|
|
1177 |
|
/** |
1178 |
< |
* Returns a random integer using a per-worker random |
1179 |
< |
* number generator with the same properties as |
1180 |
< |
* {@link java.util.Random#nextInt} |
1181 |
< |
* @return the next pseudorandom, uniformly distributed {@code int} |
1182 |
< |
* value from this worker's random number generator's sequence |
788 |
< |
*/ |
789 |
< |
public static int nextRandomInt() { |
790 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())). |
791 |
< |
nextJURandom(32); |
792 |
< |
} |
793 |
< |
|
794 |
< |
/** |
795 |
< |
* Returns a random integer using a per-worker random |
796 |
< |
* number generator with the same properties as |
797 |
< |
* {@link java.util.Random#nextInt(int)} |
798 |
< |
* @param n the bound on the random number to be returned. Must be |
799 |
< |
* positive. |
800 |
< |
* @return the next pseudorandom, uniformly distributed {@code int} |
801 |
< |
* value between {@code 0} (inclusive) and {@code n} (exclusive) |
802 |
< |
* from this worker's random number generator's sequence |
803 |
< |
* @throws IllegalArgumentException if n is not positive |
804 |
< |
*/ |
805 |
< |
public static int nextRandomInt(int n) { |
806 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())). |
807 |
< |
nextJURandomInt(n); |
808 |
< |
} |
809 |
< |
|
810 |
< |
/** |
811 |
< |
* Returns a random long using a per-worker random |
812 |
< |
* number generator with the same properties as |
813 |
< |
* {@link java.util.Random#nextLong} |
814 |
< |
* @return the next pseudorandom, uniformly distributed {@code long} |
815 |
< |
* value from this worker's random number generator's sequence |
816 |
< |
*/ |
817 |
< |
public static long nextRandomLong() { |
818 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())). |
819 |
< |
nextJURandomLong(); |
820 |
< |
} |
821 |
< |
|
822 |
< |
/** |
823 |
< |
* Returns a random integer using a per-worker random |
824 |
< |
* number generator with the same properties as |
825 |
< |
* {@link java.util.Random#nextInt(int)} |
826 |
< |
* @param n the bound on the random number to be returned. Must be |
827 |
< |
* positive. |
828 |
< |
* @return the next pseudorandom, uniformly distributed {@code int} |
829 |
< |
* value between {@code 0} (inclusive) and {@code n} (exclusive) |
830 |
< |
* from this worker's random number generator's sequence |
831 |
< |
* @throws IllegalArgumentException if n is not positive |
832 |
< |
*/ |
833 |
< |
public static long nextRandomLong(long n) { |
834 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())). |
835 |
< |
nextJURandomLong(n); |
836 |
< |
} |
837 |
< |
|
838 |
< |
/** |
839 |
< |
* Returns a random double using a per-worker random |
840 |
< |
* number generator with the same properties as |
841 |
< |
* {@link java.util.Random#nextDouble} |
842 |
< |
* @return the next pseudorandom, uniformly distributed {@code double} |
843 |
< |
* value between {@code 0.0} and {@code 1.0} from this |
844 |
< |
* worker's random number generator's sequence |
1178 |
> |
* Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. |
1179 |
> |
* Replace with a simple call to Unsafe.getUnsafe when integrating |
1180 |
> |
* into a jdk. |
1181 |
> |
* |
1182 |
> |
* @return a sun.misc.Unsafe |
1183 |
|
*/ |
1184 |
< |
public static double nextRandomDouble() { |
847 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())). |
848 |
< |
nextJURandomDouble(); |
849 |
< |
} |
850 |
< |
|
851 |
< |
// Temporary Unsafe mechanics for preliminary release |
852 |
< |
|
853 |
< |
static final Unsafe _unsafe; |
854 |
< |
static final long baseOffset; |
855 |
< |
static final long spOffset; |
856 |
< |
static final long qBase; |
857 |
< |
static final int qShift; |
858 |
< |
static final long runStateOffset; |
859 |
< |
static { |
1184 |
> |
private static sun.misc.Unsafe getUnsafe() { |
1185 |
|
try { |
1186 |
< |
if (ForkJoinWorkerThread.class.getClassLoader() != null) { |
1187 |
< |
Field f = Unsafe.class.getDeclaredField("theUnsafe"); |
1188 |
< |
f.setAccessible(true); |
1189 |
< |
_unsafe = (Unsafe)f.get(null); |
1190 |
< |
} |
1191 |
< |
else |
1192 |
< |
_unsafe = Unsafe.getUnsafe(); |
1193 |
< |
baseOffset = _unsafe.objectFieldOffset |
1194 |
< |
(ForkJoinWorkerThread.class.getDeclaredField("base")); |
1195 |
< |
spOffset = _unsafe.objectFieldOffset |
1196 |
< |
(ForkJoinWorkerThread.class.getDeclaredField("sp")); |
1197 |
< |
runStateOffset = _unsafe.objectFieldOffset |
1198 |
< |
(ForkJoinWorkerThread.class.getDeclaredField("runState")); |
1199 |
< |
qBase = _unsafe.arrayBaseOffset(ForkJoinTask[].class); |
1200 |
< |
int s = _unsafe.arrayIndexScale(ForkJoinTask[].class); |
1201 |
< |
if ((s & (s-1)) != 0) |
877 |
< |
throw new Error("data type scale not a power of two"); |
878 |
< |
qShift = 31 - Integer.numberOfLeadingZeros(s); |
879 |
< |
} catch (Exception e) { |
880 |
< |
throw new RuntimeException("Could not initialize intrinsics", e); |
1186 |
> |
return sun.misc.Unsafe.getUnsafe(); |
1187 |
> |
} catch (SecurityException se) { |
1188 |
> |
try { |
1189 |
> |
return java.security.AccessController.doPrivileged |
1190 |
> |
(new java.security |
1191 |
> |
.PrivilegedExceptionAction<sun.misc.Unsafe>() { |
1192 |
> |
public sun.misc.Unsafe run() throws Exception { |
1193 |
> |
java.lang.reflect.Field f = sun.misc |
1194 |
> |
.Unsafe.class.getDeclaredField("theUnsafe"); |
1195 |
> |
f.setAccessible(true); |
1196 |
> |
return (sun.misc.Unsafe) f.get(null); |
1197 |
> |
}}); |
1198 |
> |
} catch (java.security.PrivilegedActionException e) { |
1199 |
> |
throw new RuntimeException("Could not initialize intrinsics", |
1200 |
> |
e.getCause()); |
1201 |
> |
} |
1202 |
|
} |
1203 |
|
} |
1204 |
|
} |