1 |
|
/* |
2 |
|
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
|
* Expert Group and released to the public domain, as explained at |
4 |
< |
* http://creativecommons.org/licenses/publicdomain |
4 |
> |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
|
*/ |
6 |
|
|
7 |
|
package jsr166y; |
11 |
|
import java.util.Collection; |
12 |
|
import java.util.Collections; |
13 |
|
import java.util.List; |
14 |
+ |
import java.util.Random; |
15 |
|
import java.util.concurrent.AbstractExecutorService; |
16 |
|
import java.util.concurrent.Callable; |
17 |
|
import java.util.concurrent.ExecutorService; |
19 |
|
import java.util.concurrent.RejectedExecutionException; |
20 |
|
import java.util.concurrent.RunnableFuture; |
21 |
|
import java.util.concurrent.TimeUnit; |
21 |
– |
import java.util.concurrent.TimeoutException; |
22 |
|
import java.util.concurrent.atomic.AtomicInteger; |
23 |
< |
import java.util.concurrent.locks.LockSupport; |
24 |
< |
import java.util.concurrent.locks.ReentrantLock; |
23 |
> |
import java.util.concurrent.atomic.AtomicLong; |
24 |
> |
import java.util.concurrent.locks.AbstractQueuedSynchronizer; |
25 |
> |
import java.util.concurrent.locks.Condition; |
26 |
|
|
27 |
|
/** |
28 |
|
* An {@link ExecutorService} for running {@link ForkJoinTask}s. |
33 |
|
* <p>A {@code ForkJoinPool} differs from other kinds of {@link |
34 |
|
* ExecutorService} mainly by virtue of employing |
35 |
|
* <em>work-stealing</em>: all threads in the pool attempt to find and |
36 |
< |
* execute subtasks created by other active tasks (eventually blocking |
37 |
< |
* waiting for work if none exist). This enables efficient processing |
38 |
< |
* when most tasks spawn other subtasks (as do most {@code |
39 |
< |
* ForkJoinTask}s). When setting <em>asyncMode</em> to true in |
40 |
< |
* constructors, {@code ForkJoinPool}s may also be appropriate for use |
41 |
< |
* with event-style tasks that are never joined. |
36 |
> |
* execute tasks submitted to the pool and/or created by other active |
37 |
> |
* tasks (eventually blocking waiting for work if none exist). This |
38 |
> |
* enables efficient processing when most tasks spawn other subtasks |
39 |
> |
* (as do most {@code ForkJoinTask}s), as well as when many small |
40 |
> |
* tasks are submitted to the pool from external clients. Especially |
41 |
> |
* when setting <em>asyncMode</em> to true in constructors, {@code |
42 |
> |
* ForkJoinPool}s may also be appropriate for use with event-style |
43 |
> |
* tasks that are never joined. |
44 |
|
* |
45 |
|
* <p>A {@code ForkJoinPool} is constructed with a given target |
46 |
|
* parallelism level; by default, equal to the number of available |
60 |
|
* convenient form for informal monitoring. |
61 |
|
* |
62 |
|
* <p> As is the case with other ExecutorServices, there are three |
63 |
< |
* main task execution methods summarized in the following |
64 |
< |
* table. These are designed to be used by clients not already engaged |
65 |
< |
* in fork/join computations in the current pool. The main forms of |
66 |
< |
* these methods accept instances of {@code ForkJoinTask}, but |
67 |
< |
* overloaded forms also allow mixed execution of plain {@code |
63 |
> |
* main task execution methods summarized in the following table. |
64 |
> |
* These are designed to be used primarily by clients not already |
65 |
> |
* engaged in fork/join computations in the current pool. The main |
66 |
> |
* forms of these methods accept instances of {@code ForkJoinTask}, |
67 |
> |
* but overloaded forms also allow mixed execution of plain {@code |
68 |
|
* Runnable}- or {@code Callable}- based activities as well. However, |
69 |
< |
* tasks that are already executing in a pool should normally |
70 |
< |
* <em>NOT</em> use these pool execution methods, but instead use the |
71 |
< |
* within-computation forms listed in the table. |
69 |
> |
* tasks that are already executing in a pool should normally instead |
70 |
> |
* use the within-computation forms listed in the table unless using |
71 |
> |
* async event-style tasks that are not usually joined, in which case |
72 |
> |
* there is little difference among choice of methods. |
73 |
|
* |
74 |
|
* <table BORDER CELLPADDING=3 CELLSPACING=1> |
75 |
|
* <tr> |
104 |
|
* daemon} mode, there is typically no need to explicitly {@link |
105 |
|
* #shutdown} such a pool upon program exit. |
106 |
|
* |
107 |
< |
* <pre> |
107 |
> |
* <pre> {@code |
108 |
|
* static final ForkJoinPool mainPool = new ForkJoinPool(); |
109 |
|
* ... |
110 |
|
* public void sort(long[] array) { |
111 |
|
* mainPool.invoke(new SortTask(array, 0, array.length)); |
112 |
< |
* } |
109 |
< |
* </pre> |
112 |
> |
* }}</pre> |
113 |
|
* |
114 |
|
* <p><b>Implementation notes</b>: This implementation restricts the |
115 |
|
* maximum number of running threads to 32767. Attempts to create |
128 |
|
/* |
129 |
|
* Implementation Overview |
130 |
|
* |
131 |
< |
* This class provides the central bookkeeping and control for a |
132 |
< |
* set of worker threads: Submissions from non-FJ threads enter |
133 |
< |
* into a submission queue. Workers take these tasks and typically |
134 |
< |
* split them into subtasks that may be stolen by other workers. |
135 |
< |
* The main work-stealing mechanics implemented in class |
136 |
< |
* ForkJoinWorkerThread give first priority to processing tasks |
137 |
< |
* from their own queues (LIFO or FIFO, depending on mode), then |
138 |
< |
* to randomized FIFO steals of tasks in other worker queues, and |
139 |
< |
* lastly to new submissions. These mechanics do not consider |
140 |
< |
* affinities, loads, cache localities, etc, so rarely provide the |
141 |
< |
* best possible performance on a given machine, but portably |
142 |
< |
* provide good throughput by averaging over these factors. |
143 |
< |
* (Further, even if we did try to use such information, we do not |
144 |
< |
* usually have a basis for exploiting it. For example, some sets |
145 |
< |
* of tasks profit from cache affinities, but others are harmed by |
146 |
< |
* cache pollution effects.) |
147 |
< |
* |
148 |
< |
* Beyond work-stealing support and essential bookkeeping, the |
149 |
< |
* main responsibility of this framework is to take actions when |
150 |
< |
* one worker is waiting to join a task stolen (or always held by) |
151 |
< |
* another. Because we are multiplexing many tasks on to a pool |
152 |
< |
* of workers, we can't just let them block (as in Thread.join). |
153 |
< |
* We also cannot just reassign the joiner's run-time stack with |
154 |
< |
* another and replace it later, which would be a form of |
155 |
< |
* "continuation", that even if possible is not necessarily a good |
156 |
< |
* idea. Given that the creation costs of most threads on most |
157 |
< |
* systems mainly surrounds setting up runtime stacks, thread |
158 |
< |
* creation and switching is usually not much more expensive than |
159 |
< |
* stack creation and switching, and is more flexible). Instead we |
160 |
< |
* combine two tactics: |
131 |
> |
* This class and its nested classes provide the main |
132 |
> |
* functionality and control for a set of worker threads: |
133 |
> |
* Submissions from non-FJ threads enter into submission queues. |
134 |
> |
* Workers take these tasks and typically split them into subtasks |
135 |
> |
* that may be stolen by other workers. Preference rules give |
136 |
> |
* first priority to processing tasks from their own queues (LIFO |
137 |
> |
* or FIFO, depending on mode), then to randomized FIFO steals of |
138 |
> |
* tasks in other queues. |
139 |
> |
* |
140 |
> |
* WorkQueues |
141 |
> |
* ========== |
142 |
> |
* |
143 |
> |
* Most operations occur within work-stealing queues (in nested |
144 |
> |
* class WorkQueue). These are special forms of Deques that |
145 |
> |
* support only three of the four possible end-operations -- push, |
146 |
> |
* pop, and poll (aka steal), under the further constraints that |
147 |
> |
* push and pop are called only from the owning thread (or, as |
148 |
> |
* extended here, under a lock), while poll may be called from |
149 |
> |
* other threads. (If you are unfamiliar with them, you probably |
150 |
> |
* want to read Herlihy and Shavit's book "The Art of |
151 |
> |
* Multiprocessor programming", chapter 16 describing these in |
152 |
> |
* more detail before proceeding.) The main work-stealing queue |
153 |
> |
* design is roughly similar to those in the papers "Dynamic |
154 |
> |
* Circular Work-Stealing Deque" by Chase and Lev, SPAA 2005 |
155 |
> |
* (http://research.sun.com/scalable/pubs/index.html) and |
156 |
> |
* "Idempotent work stealing" by Michael, Saraswat, and Vechev, |
157 |
> |
* PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186). |
158 |
> |
* The main differences ultimately stem from GC requirements that |
159 |
> |
* we null out taken slots as soon as we can, to maintain as small |
160 |
> |
* a footprint as possible even in programs generating huge |
161 |
> |
* numbers of tasks. To accomplish this, we shift the CAS |
162 |
> |
* arbitrating pop vs poll (steal) from being on the indices |
163 |
> |
* ("base" and "top") to the slots themselves. So, both a |
164 |
> |
* successful pop and poll mainly entail a CAS of a slot from |
165 |
> |
* non-null to null. Because we rely on CASes of references, we |
166 |
> |
* do not need tag bits on base or top. They are simple ints as |
167 |
> |
* used in any circular array-based queue (see for example |
168 |
> |
* ArrayDeque). Updates to the indices must still be ordered in a |
169 |
> |
* way that guarantees that top == base means the queue is empty, |
170 |
> |
* but otherwise may err on the side of possibly making the queue |
171 |
> |
* appear nonempty when a push, pop, or poll have not fully |
172 |
> |
* committed. Note that this means that the poll operation, |
173 |
> |
* considered individually, is not wait-free. One thief cannot |
174 |
> |
* successfully continue until another in-progress one (or, if |
175 |
> |
* previously empty, a push) completes. However, in the |
176 |
> |
* aggregate, we ensure at least probabilistic non-blockingness. |
177 |
> |
* If an attempted steal fails, a thief always chooses a different |
178 |
> |
* random victim target to try next. So, in order for one thief to |
179 |
> |
* progress, it suffices for any in-progress poll or new push on |
180 |
> |
* any empty queue to complete. |
181 |
> |
* |
182 |
> |
* This approach also enables support of a user mode in which local |
183 |
> |
* task processing is in FIFO, not LIFO order, simply by using |
184 |
> |
* poll rather than pop. This can be useful in message-passing |
185 |
> |
* frameworks in which tasks are never joined. However neither |
186 |
> |
* mode considers affinities, loads, cache localities, etc, so |
187 |
> |
* rarely provide the best possible performance on a given |
188 |
> |
* machine, but portably provide good throughput by averaging over |
189 |
> |
* these factors. (Further, even if we did try to use such |
190 |
> |
* information, we do not usually have a basis for exploiting it. |
191 |
> |
* For example, some sets of tasks profit from cache affinities, |
192 |
> |
* but others are harmed by cache pollution effects.) |
193 |
> |
* |
194 |
> |
* WorkQueues are also used in a similar way for tasks submitted |
195 |
> |
* to the pool. We cannot mix these tasks in the same queues used |
196 |
> |
* for work-stealing (this would contaminate lifo/fifo |
197 |
> |
* processing). Instead, we loosely associate submission queues |
198 |
> |
* with submitting threads, using a form of hashing. The |
199 |
> |
* ThreadLocal Submitter class contains a value initially used as |
200 |
> |
* a hash code for choosing existing queues, but may be randomly |
201 |
> |
* repositioned upon contention with other submitters. In |
202 |
> |
* essence, submitters act like workers except that they never |
203 |
> |
* take tasks, and they are multiplexed on to a finite number of |
204 |
> |
* shared work queues. However, classes are set up so that future |
205 |
> |
* extensions could allow submitters to optionally help perform |
206 |
> |
* tasks as well. Insertion of tasks in shared mode requires a |
207 |
> |
* lock (mainly to protect in the case of resizing) but we use |
208 |
> |
* only a simple spinlock (using bits in field runState), because |
209 |
> |
* submitters encountering a busy queue move on to try or create |
210 |
> |
* other queues, so never block. |
211 |
> |
* |
212 |
> |
* Management |
213 |
> |
* ========== |
214 |
> |
* |
215 |
> |
* The main throughput advantages of work-stealing stem from |
216 |
> |
* decentralized control -- workers mostly take tasks from |
217 |
> |
* themselves or each other. We cannot negate this in the |
218 |
> |
* implementation of other management responsibilities. The main |
219 |
> |
* tactic for avoiding bottlenecks is packing nearly all |
220 |
> |
* essentially atomic control state into two volatile variables |
221 |
> |
* that are by far most often read (not written) as status and |
222 |
> |
* consistency checks. |
223 |
> |
* |
224 |
> |
* Field "ctl" contains 64 bits holding all the information needed |
225 |
> |
* to atomically decide to add, inactivate, enqueue (on an event |
226 |
> |
* queue), dequeue, and/or re-activate workers. To enable this |
227 |
> |
* packing, we restrict maximum parallelism to (1<<15)-1 (which is |
228 |
> |
* far in excess of normal operating range) to allow ids, counts, |
229 |
> |
* and their negations (used for thresholding) to fit into 16bit |
230 |
> |
* fields. |
231 |
> |
* |
232 |
> |
* Field "runState" contains 32 bits needed to register and |
233 |
> |
* deregister WorkQueues, as well as to enable shutdown. It is |
234 |
> |
* only modified under a lock (normally briefly held, but |
235 |
> |
* occasionally protecting allocations and resizings) but even |
236 |
> |
* when locked remains available to check consistency. An |
237 |
> |
* auxiliary field "growHints", also only modified under lock, |
238 |
> |
* contains a candidate index for the next WorkQueue and |
239 |
> |
* a mask for submission queue indices. |
240 |
> |
* |
241 |
> |
* Recording WorkQueues. WorkQueues are recorded in the |
242 |
> |
* "workQueues" array that is created upon pool construction and |
243 |
> |
* expanded if necessary. Updates to the array while recording |
244 |
> |
* new workers and unrecording terminated ones are protected from |
245 |
> |
* each other by a lock but the array is otherwise concurrently |
246 |
> |
* readable, and accessed directly. To simplify index-based |
247 |
> |
* operations, the array size is always a power of two, and all |
248 |
> |
* readers must tolerate null slots. Shared (submission) queues |
249 |
> |
* are at even indices, worker queues at odd indices. Grouping |
250 |
> |
* them together in this way simplifies and speeds up task |
251 |
> |
* scanning. To avoid flailing during start-up, the array is |
252 |
> |
* presized to hold twice #parallelism workers (which is unlikely |
253 |
> |
* to need further resizing during execution). But to avoid |
254 |
> |
* dealing with so many null slots, variable runState includes a |
255 |
> |
* mask for the nearest power of two that contains all currently |
256 |
> |
* used indices. |
257 |
> |
* |
258 |
> |
* All worker thread creation is on-demand, triggered by task |
259 |
> |
* submissions, replacement of terminated workers, and/or |
260 |
> |
* compensation for blocked workers. However, all other support |
261 |
> |
* code is set up to work with other policies. To ensure that we |
262 |
> |
* do not hold on to worker references that would prevent GC, ALL |
263 |
> |
* accesses to workQueues are via indices into the workQueues |
264 |
> |
* array (which is one source of some of the messy code |
265 |
> |
* constructions here). In essence, the workQueues array serves as |
266 |
> |
* a weak reference mechanism. Thus for example the wait queue |
267 |
> |
* field of ctl stores indices, not references. Access to the |
268 |
> |
* workQueues in associated methods (for example signalWork) must |
269 |
> |
* both index-check and null-check the IDs. All such accesses |
270 |
> |
* ignore bad IDs by returning out early from what they are doing, |
271 |
> |
* since this can only be associated with termination, in which |
272 |
> |
* case it is OK to give up. All uses of the workQueues array |
273 |
> |
* also check that it is non-null (even if previously |
274 |
> |
* non-null). This allows nulling during termination, which is |
275 |
> |
* currently not necessary, but remains an option for |
276 |
> |
* resource-revocation-based shutdown schemes. It also helps |
277 |
> |
* reduce JIT issuance of uncommon-trap code, which tends to |
278 |
> |
* unnecessarily complicate control flow in some methods. |
279 |
> |
* |
280 |
> |
* Event Queuing. Unlike HPC work-stealing frameworks, we cannot |
281 |
> |
* let workers spin indefinitely scanning for tasks when none can |
282 |
> |
* be found immediately, and we cannot start/resume workers unless |
283 |
> |
* there appear to be tasks available. On the other hand, we must |
284 |
> |
* quickly prod them into action when new tasks are submitted or |
285 |
> |
* generated. In many usages, ramp-up time to activate workers is |
286 |
> |
* the main limiting factor in overall performance (this is |
287 |
> |
* compounded at program start-up by JIT compilation and |
288 |
> |
* allocation). So we try to streamline this as much as possible. |
289 |
> |
* We park/unpark workers after placing in an event wait queue |
290 |
> |
* when they cannot find work. This "queue" is actually a simple |
291 |
> |
* Treiber stack, headed by the "id" field of ctl, plus a 15bit |
292 |
> |
* counter value (that reflects the number of times a worker has |
293 |
> |
* been inactivated) to avoid ABA effects (we need only as many |
294 |
> |
* version numbers as worker threads). Successors are held in |
295 |
> |
* field WorkQueue.nextWait. Queuing deals with several intrinsic |
296 |
> |
* races, mainly that a task-producing thread can miss seeing (and |
297 |
> |
* signalling) another thread that gave up looking for work but |
298 |
> |
* has not yet entered the wait queue. We solve this by requiring |
299 |
> |
* a full sweep of all workers (via repeated calls to method |
300 |
> |
* scan()) both before and after a newly waiting worker is added |
301 |
> |
* to the wait queue. During a rescan, the worker might release |
302 |
> |
* some other queued worker rather than itself, which has the same |
303 |
> |
* net effect. Because enqueued workers may actually be rescanning |
304 |
> |
* rather than waiting, we set and clear the "parker" field of |
305 |
> |
* WorkQueues to reduce unnecessary calls to unpark. (This |
306 |
> |
* requires a secondary recheck to avoid missed signals.) Note |
307 |
> |
* the unusual conventions about Thread.interrupts surrounding |
308 |
> |
* parking and other blocking: Because interrupts are used solely |
309 |
> |
* to alert threads to check termination, which is checked anyway |
310 |
> |
* upon blocking, we clear status (using Thread.interrupted) |
311 |
> |
* before any call to park, so that park does not immediately |
312 |
> |
* return due to status being set via some other unrelated call to |
313 |
> |
* interrupt in user code. |
314 |
> |
* |
315 |
> |
* Signalling. We create or wake up workers only when there |
316 |
> |
* appears to be at least one task they might be able to find and |
317 |
> |
* execute. When a submission is added or another worker adds a |
318 |
> |
* task to a queue that previously had fewer than two tasks, they |
319 |
> |
* signal waiting workers (or trigger creation of new ones if |
320 |
> |
* fewer than the given parallelism level -- see signalWork). |
321 |
> |
* These primary signals are buttressed by signals during rescans; |
322 |
> |
* together these cover the signals needed in cases when more |
323 |
> |
* tasks are pushed but untaken, and improve performance compared |
324 |
> |
* to having one thread wake up all workers. |
325 |
> |
* |
326 |
> |
* Trimming workers. To release resources after periods of lack of |
327 |
> |
* use, a worker starting to wait when the pool is quiescent will |
328 |
> |
* time out and terminate if the pool has remained quiescent for |
329 |
> |
* SHRINK_RATE nanosecs. This will slowly propagate, eventually |
330 |
> |
* terminating all workers after long periods of non-use. |
331 |
> |
* |
332 |
> |
* Shutdown and Termination. A call to shutdownNow atomically sets |
333 |
> |
* a runState bit and then (non-atomically) sets each worker's |
334 |
> |
* runState status, cancels all unprocessed tasks, and wakes up |
335 |
> |
* all waiting workers. Detecting whether termination should |
336 |
> |
* commence after a non-abrupt shutdown() call requires more work |
337 |
> |
* and bookkeeping. We need consensus about quiescence (i.e., that |
338 |
> |
* there is no more work). The active count provides a primary |
339 |
> |
* indication but non-abrupt shutdown still requires a rechecking |
340 |
> |
* scan for any workers that are inactive but not queued. |
341 |
> |
* |
342 |
> |
* Joining Tasks |
343 |
> |
* ============= |
344 |
> |
* |
345 |
> |
* Any of several actions may be taken when one worker is waiting |
346 |
> |
* to join a task stolen (or always held) by another. Because we |
347 |
> |
* are multiplexing many tasks on to a pool of workers, we can't |
348 |
> |
* just let them block (as in Thread.join). We also cannot just |
349 |
> |
* reassign the joiner's run-time stack with another and replace |
350 |
> |
* it later, which would be a form of "continuation", that even if |
351 |
> |
* possible is not necessarily a good idea since we sometimes need |
352 |
> |
* both an unblocked task and its continuation to progress. |
353 |
> |
* Instead we combine two tactics: |
354 |
|
* |
355 |
|
* Helping: Arranging for the joiner to execute some task that it |
356 |
< |
* would be running if the steal had not occurred. Method |
161 |
< |
* ForkJoinWorkerThread.helpJoinTask tracks joining->stealing |
162 |
< |
* links to try to find such a task. |
356 |
> |
* would be running if the steal had not occurred. |
357 |
|
* |
358 |
|
* Compensating: Unless there are already enough live threads, |
359 |
< |
* method helpMaintainParallelism() may create or |
360 |
< |
* re-activate a spare thread to compensate for blocked |
167 |
< |
* joiners until they unblock. |
359 |
> |
* method tryCompensate() may create or re-activate a spare |
360 |
> |
* thread to compensate for blocked joiners until they unblock. |
361 |
|
* |
362 |
< |
* It is impossible to keep exactly the target (parallelism) |
363 |
< |
* number of threads running at any given time. Determining |
364 |
< |
* existence of conservatively safe helping targets, the |
365 |
< |
* availability of already-created spares, and the apparent need |
366 |
< |
* to create new spares are all racy and require heuristic |
367 |
< |
* guidance, so we rely on multiple retries of each. Compensation |
368 |
< |
* occurs in slow-motion. It is triggered only upon timeouts of |
176 |
< |
* Object.wait used for joins. This reduces poor decisions that |
177 |
< |
* would otherwise be made when threads are waiting for others |
178 |
< |
* that are stalled because of unrelated activities such as |
179 |
< |
* garbage collection. |
362 |
> |
* A third form (implemented in tryRemoveAndExec and |
363 |
> |
* tryPollForAndExec) amounts to helping a hypothetical |
364 |
> |
* compensator: If we can readily tell that a possible action of a |
365 |
> |
* compensator is to steal and execute the task being joined, the |
366 |
> |
* joining thread can do so directly, without the need for a |
367 |
> |
* compensation thread (although at the expense of larger run-time |
368 |
> |
* stacks, but the tradeoff is typically worthwhile). |
369 |
|
* |
370 |
|
* The ManagedBlocker extension API can't use helping so relies |
371 |
|
* only on compensation in method awaitBlocker. |
372 |
|
* |
373 |
< |
* The main throughput advantages of work-stealing stem from |
374 |
< |
* decentralized control -- workers mostly steal tasks from each |
375 |
< |
* other. We do not want to negate this by creating bottlenecks |
376 |
< |
* implementing other management responsibilities. So we use a |
377 |
< |
* collection of techniques that avoid, reduce, or cope well with |
378 |
< |
* contention. These entail several instances of bit-packing into |
379 |
< |
* CASable fields to maintain only the minimally required |
380 |
< |
* atomicity. To enable such packing, we restrict maximum |
381 |
< |
* parallelism to (1<<15)-1 (enabling twice this (to accommodate |
382 |
< |
* unbalanced increments and decrements) to fit into a 16 bit |
383 |
< |
* field, which is far in excess of normal operating range. Even |
384 |
< |
* though updates to some of these bookkeeping fields do sometimes |
385 |
< |
* contend with each other, they don't normally cache-contend with |
386 |
< |
* updates to others enough to warrant memory padding or |
387 |
< |
* isolation. So they are all held as fields of ForkJoinPool |
388 |
< |
* objects. The main capabilities are as follows: |
389 |
< |
* |
390 |
< |
* 1. Creating and removing workers. Workers are recorded in the |
391 |
< |
* "workers" array. This is an array as opposed to some other data |
392 |
< |
* structure to support index-based random steals by workers. |
393 |
< |
* Updates to the array recording new workers and unrecording |
394 |
< |
* terminated ones are protected from each other by a lock |
395 |
< |
* (workerLock) but the array is otherwise concurrently readable, |
396 |
< |
* and accessed directly by workers. To simplify index-based |
397 |
< |
* operations, the array size is always a power of two, and all |
398 |
< |
* readers must tolerate null slots. Currently, all worker thread |
399 |
< |
* creation is on-demand, triggered by task submissions, |
400 |
< |
* replacement of terminated workers, and/or compensation for |
401 |
< |
* blocked workers. However, all other support code is set up to |
213 |
< |
* work with other policies. |
214 |
< |
* |
215 |
< |
* To ensure that we do not hold on to worker references that |
216 |
< |
* would prevent GC, ALL accesses to workers are via indices into |
217 |
< |
* the workers array (which is one source of some of the unusual |
218 |
< |
* code constructions here). In essence, the workers array serves |
219 |
< |
* as a WeakReference mechanism. Thus for example the event queue |
220 |
< |
* stores worker indices, not worker references. Access to the |
221 |
< |
* workers in associated methods (for example releaseEventWaiters) |
222 |
< |
* must both index-check and null-check the IDs. All such accesses |
223 |
< |
* ignore bad IDs by returning out early from what they are doing, |
224 |
< |
* since this can only be associated with shutdown, in which case |
225 |
< |
* it is OK to give up. On termination, we just clobber these |
226 |
< |
* data structures without trying to use them. |
227 |
< |
* |
228 |
< |
* 2. Bookkeeping for dynamically adding and removing workers. We |
229 |
< |
* aim to approximately maintain the given level of parallelism. |
230 |
< |
* When some workers are known to be blocked (on joins or via |
231 |
< |
* ManagedBlocker), we may create or resume others to take their |
232 |
< |
* place until they unblock (see below). Implementing this |
233 |
< |
* requires counts of the number of "running" threads (i.e., those |
234 |
< |
* that are neither blocked nor artificially suspended) as well as |
235 |
< |
* the total number. These two values are packed into one field, |
236 |
< |
* "workerCounts" because we need accurate snapshots when deciding |
237 |
< |
* to create, resume or suspend. Note however that the |
238 |
< |
* correspondence of these counts to reality is not guaranteed. In |
239 |
< |
* particular updates for unblocked threads may lag until they |
240 |
< |
* actually wake up. |
241 |
< |
* |
242 |
< |
* 3. Maintaining global run state. The run state of the pool |
243 |
< |
* consists of a runLevel (SHUTDOWN, TERMINATING, etc) similar to |
244 |
< |
* those in other Executor implementations, as well as a count of |
245 |
< |
* "active" workers -- those that are, or soon will be, or |
246 |
< |
* recently were executing tasks. The runLevel and active count |
247 |
< |
* are packed together in order to correctly trigger shutdown and |
248 |
< |
* termination. Without care, active counts can be subject to very |
249 |
< |
* high contention. We substantially reduce this contention by |
250 |
< |
* relaxing update rules. A worker must claim active status |
251 |
< |
* prospectively, by activating if it sees that a submitted or |
252 |
< |
* stealable task exists (it may find after activating that the |
253 |
< |
* task no longer exists). It stays active while processing this |
254 |
< |
* task (if it exists) and any other local subtasks it produces, |
255 |
< |
* until it cannot find any other tasks. It then tries |
256 |
< |
* inactivating (see method preStep), but upon update contention |
257 |
< |
* instead scans for more tasks, later retrying inactivation if it |
258 |
< |
* doesn't find any. |
259 |
< |
* |
260 |
< |
* 4. Managing idle workers waiting for tasks. We cannot let |
261 |
< |
* workers spin indefinitely scanning for tasks when none are |
262 |
< |
* available. On the other hand, we must quickly prod them into |
263 |
< |
* action when new tasks are submitted or generated. We |
264 |
< |
* park/unpark these idle workers using an event-count scheme. |
265 |
< |
* Field eventCount is incremented upon events that may enable |
266 |
< |
* workers that previously could not find a task to now find one: |
267 |
< |
* Submission of a new task to the pool, or another worker pushing |
268 |
< |
* a task onto a previously empty queue. (We also use this |
269 |
< |
* mechanism for configuration and termination actions that |
270 |
< |
* require wakeups of idle workers). Each worker maintains its |
271 |
< |
* last known event count, and blocks when a scan for work did not |
272 |
< |
* find a task AND its lastEventCount matches the current |
273 |
< |
* eventCount. Waiting idle workers are recorded in a variant of |
274 |
< |
* Treiber stack headed by field eventWaiters which, when nonzero, |
275 |
< |
* encodes the thread index and count awaited for by the worker |
276 |
< |
* thread most recently calling eventSync. This thread in turn has |
277 |
< |
* a record (field nextEventWaiter) for the next waiting worker. |
278 |
< |
* In addition to allowing simpler decisions about need for |
279 |
< |
* wakeup, the event count bits in eventWaiters serve the role of |
280 |
< |
* tags to avoid ABA errors in Treiber stacks. Upon any wakeup, |
281 |
< |
* released threads also try to release at most two others. The |
282 |
< |
* net effect is a tree-like diffusion of signals, where released |
283 |
< |
* threads (and possibly others) help with unparks. To further |
284 |
< |
* reduce contention effects a bit, failed CASes to increment |
285 |
< |
* field eventCount are tolerated without retries in signalWork. |
286 |
< |
* Conceptually they are merged into the same event, which is OK |
287 |
< |
* when their only purpose is to enable workers to scan for work. |
288 |
< |
* |
289 |
< |
* 5. Managing suspension of extra workers. When a worker notices |
290 |
< |
* (usually upon timeout of a wait()) that there are too few |
291 |
< |
* running threads, we may create a new thread to maintain |
292 |
< |
* parallelism level, or at least avoid starvation. Usually, extra |
293 |
< |
* threads are needed for only very short periods, yet join |
294 |
< |
* dependencies are such that we sometimes need them in |
295 |
< |
* bursts. Rather than create new threads each time this happens, |
296 |
< |
* we suspend no-longer-needed extra ones as "spares". For most |
297 |
< |
* purposes, we don't distinguish "extra" spare threads from |
298 |
< |
* normal "core" threads: On each call to preStep (the only point |
299 |
< |
* at which we can do this) a worker checks to see if there are |
300 |
< |
* now too many running workers, and if so, suspends itself. |
301 |
< |
* Method helpMaintainParallelism looks for suspended threads to |
302 |
< |
* resume before considering creating a new replacement. The |
303 |
< |
* spares themselves are encoded on another variant of a Treiber |
304 |
< |
* Stack, headed at field "spareWaiters". Note that the use of |
305 |
< |
* spares is intrinsically racy. One thread may become a spare at |
306 |
< |
* about the same time as another is needlessly being created. We |
307 |
< |
* counteract this and related slop in part by requiring resumed |
308 |
< |
* spares to immediately recheck (in preStep) to see whether they |
309 |
< |
* should re-suspend. |
310 |
< |
* |
311 |
< |
* 6. Killing off unneeded workers. A timeout mechanism is used to |
312 |
< |
* shed unused workers: The oldest (first) event queue waiter uses |
313 |
< |
* a timed rather than hard wait. When this wait times out without |
314 |
< |
* a normal wakeup, it tries to shutdown any one (for convenience |
315 |
< |
* the newest) other spare or event waiter via |
316 |
< |
* tryShutdownUnusedWorker. This eventually reduces the number of |
317 |
< |
* worker threads to a minimum of one after a long enough period |
318 |
< |
* without use. |
319 |
< |
* |
320 |
< |
* 7. Deciding when to create new workers. The main dynamic |
321 |
< |
* control in this class is deciding when to create extra threads |
322 |
< |
* in method helpMaintainParallelism. We would like to keep |
323 |
< |
* exactly #parallelism threads running, which is an impossible |
324 |
< |
* task. We always need to create one when the number of running |
325 |
< |
* threads would become zero and all workers are busy. Beyond |
326 |
< |
* this, we must rely on heuristics that work well in the |
327 |
< |
* presence of transient phenomena such as GC stalls, dynamic |
328 |
< |
* compilation, and wake-up lags. These transients are extremely |
329 |
< |
* common -- we are normally trying to fully saturate the CPUs on |
330 |
< |
* a machine, so almost any activity other than running tasks |
331 |
< |
* impedes accuracy. Our main defense is to allow parallelism to |
332 |
< |
* lapse for a while during joins, and use a timeout to see if, |
333 |
< |
* after the resulting settling, there is still a need for |
334 |
< |
* additional workers. This also better copes with the fact that |
335 |
< |
* some of the methods in this class tend to never become compiled |
336 |
< |
* (but are interpreted), so some components of the entire set of |
337 |
< |
* controls might execute 100 times faster than others. And |
338 |
< |
* similarly for cases where the apparent lack of work is just due |
339 |
< |
* to GC stalls and other transient system activity. |
373 |
> |
* The algorithm in tryHelpStealer entails a form of "linear" |
374 |
> |
* helping: Each worker records (in field currentSteal) the most |
375 |
> |
* recent task it stole from some other worker. Plus, it records |
376 |
> |
* (in field currentJoin) the task it is currently actively |
377 |
> |
* joining. Method tryHelpStealer uses these markers to try to |
378 |
> |
* find a worker to help (i.e., steal back a task from and execute |
379 |
> |
* it) that could hasten completion of the actively joined task. |
380 |
> |
* In essence, the joiner executes a task that would be on its own |
381 |
> |
* local deque had the to-be-joined task not been stolen. This may |
382 |
> |
* be seen as a conservative variant of the approach in Wagner & |
383 |
> |
* Calder "Leapfrogging: a portable technique for implementing |
384 |
> |
* efficient futures" SIGPLAN Notices, 1993 |
385 |
> |
* (http://portal.acm.org/citation.cfm?id=155354). It differs in |
386 |
> |
* that: (1) We only maintain dependency links across workers upon |
387 |
> |
* steals, rather than use per-task bookkeeping. This sometimes |
388 |
> |
* requires a linear scan of workQueues array to locate stealers, but |
389 |
> |
* often doesn't because stealers leave hints (that may become |
390 |
> |
* stale/wrong) of where to locate them. A stealHint is only a |
391 |
> |
* hint because a worker might have had multiple steals and the |
392 |
> |
* hint records only one of them (usually the most current). |
393 |
> |
* Hinting isolates cost to when it is needed, rather than adding |
394 |
> |
* to per-task overhead. (2) It is "shallow", ignoring nesting |
395 |
> |
* and potentially cyclic mutual steals. (3) It is intentionally |
396 |
> |
* racy: field currentJoin is updated only while actively joining, |
397 |
> |
* which means that we miss links in the chain during long-lived |
398 |
> |
* tasks, GC stalls etc (which is OK since blocking in such cases |
399 |
> |
* is usually a good idea). (4) We bound the number of attempts |
400 |
> |
* to find work (see MAX_HELP_DEPTH) and fall back to suspending |
401 |
> |
* the worker and if necessary replacing it with another. |
402 |
|
* |
403 |
< |
* Beware that there is a lot of representation-level coupling |
403 |
> |
* It is impossible to keep exactly the target parallelism number |
404 |
> |
* of threads running at any given time. Determining the |
405 |
> |
* existence of conservatively safe helping targets, the |
406 |
> |
* availability of already-created spares, and the apparent need |
407 |
> |
* to create new spares are all racy, so we rely on multiple |
408 |
> |
* retries of each. Currently, in keeping with on-demand |
409 |
> |
* signalling policy, we compensate only if blocking would leave |
410 |
> |
* less than one active (non-waiting, non-blocked) worker. |
411 |
> |
* Additionally, to avoid some false alarms due to GC, lagging |
412 |
> |
* counters, system activity, etc, compensated blocking for joins |
413 |
> |
* is only attempted after rechecks stabilize in |
414 |
> |
* ForkJoinTask.awaitJoin. (Retries are interspersed with |
415 |
> |
* Thread.yield, for good citizenship.) |
416 |
> |
* |
417 |
> |
* Style notes: There is a lot of representation-level coupling |
418 |
|
* among classes ForkJoinPool, ForkJoinWorkerThread, and |
419 |
< |
* ForkJoinTask. For example, direct access to "workers" array by |
420 |
< |
* workers, and direct access to ForkJoinTask.status by both |
421 |
< |
* ForkJoinPool and ForkJoinWorkerThread. There is little point |
422 |
< |
* trying to reduce this, since any associated future changes in |
423 |
< |
* representations will need to be accompanied by algorithmic |
424 |
< |
* changes anyway. |
425 |
< |
* |
426 |
< |
* Style notes: There are lots of inline assignments (of form |
427 |
< |
* "while ((local = field) != 0)") which are usually the simplest |
428 |
< |
* way to ensure the required read orderings (which are sometimes |
429 |
< |
* critical). Also several occurrences of the unusual "do {} |
430 |
< |
* while (!cas...)" which is the simplest way to force an update of |
431 |
< |
* a CAS'ed variable. There are also other coding oddities that |
432 |
< |
* help some methods perform reasonably even when interpreted (not |
433 |
< |
* compiled), at the expense of some messy constructions that |
434 |
< |
* reduce byte code counts. |
435 |
< |
* |
436 |
< |
* The order of declarations in this file is: (1) statics (2) |
437 |
< |
* fields (along with constants used when unpacking some of them) |
438 |
< |
* (3) internal control methods (4) callbacks and other support |
439 |
< |
* for ForkJoinTask and ForkJoinWorkerThread classes, (5) exported |
440 |
< |
* methods (plus a few little helpers). |
419 |
> |
* ForkJoinTask. The fields of WorkQueue maintain data structures |
420 |
> |
* managed by ForkJoinPool, so are directly accessed. There is |
421 |
> |
* little point trying to reduce this, since any associated future |
422 |
> |
* changes in representations will need to be accompanied by |
423 |
> |
* algorithmic changes anyway. Several methods intrinsically |
424 |
> |
* sprawl because they must accumulate sets of consistent reads of |
425 |
> |
* volatiles held in local variables. Methods signalWork() and |
426 |
> |
* scan() are the main bottlenecks, so are especially heavily |
427 |
> |
* micro-optimized/mangled. There are lots of inline assignments |
428 |
> |
* (of form "while ((local = field) != 0)") which are usually the |
429 |
> |
* simplest way to ensure the required read orderings (which are |
430 |
> |
* sometimes critical). This leads to a "C"-like style of listing |
431 |
> |
* declarations of these locals at the heads of methods or blocks. |
432 |
> |
* There are several occurrences of the unusual "do {} while |
433 |
> |
* (!cas...)" which is the simplest way to force an update of a |
434 |
> |
* CAS'ed variable. There are also other coding oddities that help |
435 |
> |
* some methods perform reasonably even when interpreted (not |
436 |
> |
* compiled). |
437 |
> |
* |
438 |
> |
* The order of declarations in this file is: |
439 |
> |
* (1) Static utility functions |
440 |
> |
* (2) Nested (static) classes |
441 |
> |
* (3) Static fields |
442 |
> |
* (4) Fields, along with constants used when unpacking some of them |
443 |
> |
* (5) Internal control methods |
444 |
> |
* (6) Callbacks and other support for ForkJoinTask methods |
445 |
> |
* (7) Exported methods |
446 |
> |
* (8) Static block initializing statics in minimally dependent order |
447 |
> |
*/ |
448 |
> |
|
449 |
> |
// Static utilities |
450 |
> |
|
451 |
> |
/** |
452 |
> |
* Computes an initial hash code (also serving as a non-zero |
453 |
> |
* random seed) for a thread id. This method is expected to |
454 |
> |
* provide higher-quality hash codes than using method hashCode(). |
455 |
> |
*/ |
456 |
> |
static final int hashId(long id) { |
457 |
> |
int h = (int)id ^ (int)(id >>> 32); // Use MurmurHash of thread id |
458 |
> |
h ^= h >>> 16; h *= 0x85ebca6b; |
459 |
> |
h ^= h >>> 13; h *= 0xc2b2ae35; |
460 |
> |
h ^= h >>> 16; |
461 |
> |
return (h == 0)? 1 : h; // ensure nonzero |
462 |
> |
} |
463 |
> |
|
464 |
> |
/** |
465 |
> |
* If there is a security manager, makes sure caller has |
466 |
> |
* permission to modify threads. |
467 |
|
*/ |
468 |
+ |
private static void checkPermission() { |
469 |
+ |
SecurityManager security = System.getSecurityManager(); |
470 |
+ |
if (security != null) |
471 |
+ |
security.checkPermission(modifyThreadPermission); |
472 |
+ |
} |
473 |
+ |
|
474 |
+ |
// Nested classes |
475 |
|
|
476 |
|
/** |
477 |
|
* Factory for creating new {@link ForkJoinWorkerThread}s. |
501 |
|
} |
502 |
|
|
503 |
|
/** |
504 |
< |
* Creates a new ForkJoinWorkerThread. This factory is used unless |
505 |
< |
* overridden in ForkJoinPool constructors. |
504 |
> |
* A simple non-reentrant lock used for exclusion when managing |
505 |
> |
* queues and workers. We use a custom lock so that we can readily |
506 |
> |
* probe lock state in constructions that check among alternative |
507 |
> |
* actions. The lock is normally only very briefly held, and |
508 |
> |
* sometimes treated as a spinlock, but other usages block to |
509 |
> |
* reduce overall contention in those cases where locked code |
510 |
> |
* bodies perform allocation/resizing. |
511 |
> |
*/ |
512 |
> |
static final class Mutex extends AbstractQueuedSynchronizer { |
513 |
> |
public final boolean tryAcquire(int ignore) { |
514 |
> |
return compareAndSetState(0, 1); |
515 |
> |
} |
516 |
> |
public final boolean tryRelease(int ignore) { |
517 |
> |
setState(0); |
518 |
> |
return true; |
519 |
> |
} |
520 |
> |
public final void lock() { acquire(0); } |
521 |
> |
public final void unlock() { release(0); } |
522 |
> |
public final boolean isHeldExclusively() { return getState() == 1; } |
523 |
> |
public final Condition newCondition() { return new ConditionObject(); } |
524 |
> |
} |
525 |
> |
|
526 |
> |
/** |
527 |
> |
* Class for artificial tasks that are used to replace the target |
528 |
> |
* of local joins if they are removed from an interior queue slot |
529 |
> |
* in WorkQueue.tryRemoveAndExec. We don't need the proxy to |
530 |
> |
* actually do anything beyond having a unique identity. |
531 |
> |
*/ |
532 |
> |
static final class EmptyTask extends ForkJoinTask<Void> { |
533 |
> |
EmptyTask() { status = ForkJoinTask.NORMAL; } // force done |
534 |
> |
public final Void getRawResult() { return null; } |
535 |
> |
public final void setRawResult(Void x) {} |
536 |
> |
public final boolean exec() { return true; } |
537 |
> |
} |
538 |
> |
|
539 |
> |
/** |
540 |
> |
* Queues supporting work-stealing as well as external task |
541 |
> |
* submission. See above for main rationale and algorithms. |
542 |
> |
* Implementation relies heavily on "Unsafe" intrinsics |
543 |
> |
* and selective use of "volatile": |
544 |
> |
* |
545 |
> |
* Field "base" is the index (mod array.length) of the least valid |
546 |
> |
* queue slot, which is always the next position to steal (poll) |
547 |
> |
* from if nonempty. Reads and writes require volatile orderings |
548 |
> |
* but not CAS, because updates are only performed after slot |
549 |
> |
* CASes. |
550 |
> |
* |
551 |
> |
* Field "top" is the index (mod array.length) of the next queue |
552 |
> |
* slot to push to or pop from. It is written only by owner thread |
553 |
> |
* for push, or under lock for trySharedPush, and accessed by |
554 |
> |
* other threads only after reading (volatile) base. Both top and |
555 |
> |
* base are allowed to wrap around on overflow, but (top - base) |
556 |
> |
* (or more commonly -(base - top) to force volatile read of base |
557 |
> |
* before top) still estimates size. |
558 |
> |
* |
559 |
> |
* The array slots are read and written using the emulation of |
560 |
> |
* volatiles/atomics provided by Unsafe. Insertions must in |
561 |
> |
* general use putOrderedObject as a form of releasing store to |
562 |
> |
* ensure that all writes to the task object are ordered before |
563 |
> |
* its publication in the queue. (Although we can avoid one case |
564 |
> |
* of this when locked in trySharedPush.) All removals entail a |
565 |
> |
* CAS to null. The array is always a power of two. To ensure |
566 |
> |
* safety of Unsafe array operations, all accesses perform |
567 |
> |
* explicit null checks and implicit bounds checks via |
568 |
> |
* power-of-two masking. |
569 |
> |
* |
570 |
> |
* In addition to basic queuing support, this class contains |
571 |
> |
* fields described elsewhere to control execution. It turns out |
572 |
> |
* to work better memory-layout-wise to include them in this |
573 |
> |
* class rather than a separate class. |
574 |
> |
* |
575 |
> |
* Performance on most platforms is very sensitive to placement of |
576 |
> |
* instances of both WorkQueues and their arrays -- we absolutely |
577 |
> |
* do not want multiple WorkQueue instances or multiple queue |
578 |
> |
* arrays sharing cache lines. (It would be best for queue objects |
579 |
> |
* and their arrays to share, but there is nothing available to |
580 |
> |
* help arrange that). Unfortunately, because they are recorded |
581 |
> |
* in a common array, WorkQueue instances are often moved to be |
582 |
> |
* adjacent by garbage collectors. To reduce impact, we use field |
583 |
> |
* padding that works OK on common platforms; this effectively |
584 |
> |
* trades off slightly slower average field access for the sake of |
585 |
> |
* avoiding really bad worst-case access. (Until better JVM |
586 |
> |
* support is in place, this padding is dependent on transient |
587 |
> |
* properties of JVM field layout rules.) We also take care in |
588 |
> |
* allocating, sizing and resizing the array. Non-shared queue |
589 |
> |
* arrays are initialized (via method growArray) by workers before |
590 |
> |
* use. Others are allocated on first use. |
591 |
|
*/ |
592 |
< |
public static final ForkJoinWorkerThreadFactory |
593 |
< |
defaultForkJoinWorkerThreadFactory = |
594 |
< |
new DefaultForkJoinWorkerThreadFactory(); |
592 |
> |
static final class WorkQueue { |
593 |
> |
/** |
594 |
> |
* Capacity of work-stealing queue array upon initialization. |
595 |
> |
* Must be a power of two; at least 4, but set larger to |
596 |
> |
* reduce cacheline sharing among queues. |
597 |
> |
*/ |
598 |
> |
static final int INITIAL_QUEUE_CAPACITY = 1 << 8; |
599 |
|
|
600 |
< |
/** |
601 |
< |
* Permission required for callers of methods that may start or |
602 |
< |
* kill threads. |
603 |
< |
*/ |
604 |
< |
private static final RuntimePermission modifyThreadPermission = |
605 |
< |
new RuntimePermission("modifyThread"); |
600 |
> |
/** |
601 |
> |
* Maximum size for queue arrays. Must be a power of two less |
602 |
> |
* than or equal to 1 << (31 - width of array entry) to ensure |
603 |
> |
* lack of wraparound of index calculations, but defined to a |
604 |
> |
* value a bit less than this to help users trap runaway |
605 |
> |
* programs before saturating systems. |
606 |
> |
*/ |
607 |
> |
static final int MAXIMUM_QUEUE_CAPACITY = 1 << 26; // 64M |
608 |
|
|
609 |
< |
/** |
610 |
< |
* If there is a security manager, makes sure caller has |
611 |
< |
* permission to modify threads. |
612 |
< |
*/ |
613 |
< |
private static void checkPermission() { |
614 |
< |
SecurityManager security = System.getSecurityManager(); |
615 |
< |
if (security != null) |
616 |
< |
security.checkPermission(modifyThreadPermission); |
617 |
< |
} |
609 |
> |
volatile long totalSteals; // cumulative number of steals |
610 |
> |
int seed; // for random scanning; initialize nonzero |
611 |
> |
volatile int eventCount; // encoded inactivation count; < 0 if inactive |
612 |
> |
int nextWait; // encoded record of next event waiter |
613 |
> |
int rescans; // remaining scans until block |
614 |
> |
int nsteals; // top-level task executions since last idle |
615 |
> |
final int mode; // lifo, fifo, or shared |
616 |
> |
int poolIndex; // index of this queue in pool (or 0) |
617 |
> |
int stealHint; // index of most recent known stealer |
618 |
> |
volatile int runState; // 1: locked, -1: terminate; else 0 |
619 |
> |
volatile int base; // index of next slot for poll |
620 |
> |
int top; // index of next slot for push |
621 |
> |
ForkJoinTask<?>[] array; // the elements (initially unallocated) |
622 |
> |
final ForkJoinWorkerThread owner; // owning thread or null if shared |
623 |
> |
volatile Thread parker; // == owner during call to park; else null |
624 |
> |
ForkJoinTask<?> currentJoin; // task being joined in awaitJoin |
625 |
> |
ForkJoinTask<?> currentSteal; // current non-local task being executed |
626 |
> |
// Heuristic padding to ameliorate unfortunate memory placements |
627 |
> |
Object p00, p01, p02, p03, p04, p05, p06, p07, p08, p09, p0a; |
628 |
> |
|
629 |
> |
WorkQueue(ForkJoinWorkerThread owner, int mode) { |
630 |
> |
this.owner = owner; |
631 |
> |
this.mode = mode; |
632 |
> |
// Place indices in the center of array (that is not yet allocated) |
633 |
> |
base = top = INITIAL_QUEUE_CAPACITY >>> 1; |
634 |
> |
} |
635 |
|
|
636 |
< |
/** |
637 |
< |
* Generator for assigning sequence numbers as pool names. |
638 |
< |
*/ |
639 |
< |
private static final AtomicInteger poolNumberGenerator = |
640 |
< |
new AtomicInteger(); |
636 |
> |
/** |
637 |
> |
* Returns number of tasks in the queue. |
638 |
> |
*/ |
639 |
> |
final int queueSize() { |
640 |
> |
int n = base - top; // non-owner callers must read base first |
641 |
> |
return (n >= 0) ? 0 : -n; |
642 |
> |
} |
643 |
|
|
644 |
< |
/** |
645 |
< |
* The time to block in a join (see awaitJoin) before checking if |
646 |
< |
* a new worker should be (re)started to maintain parallelism |
647 |
< |
* level. The value should be short enough to maintain global |
648 |
< |
* responsiveness and progress but long enough to avoid |
649 |
< |
* counterproductive firings during GC stalls or unrelated system |
650 |
< |
* activity, and to not bog down systems with continual re-firings |
651 |
< |
* on GCs or legitimately long waits. |
652 |
< |
*/ |
653 |
< |
private static final long JOIN_TIMEOUT_MILLIS = 250L; // 4 per second |
644 |
> |
/** |
645 |
> |
* Pushes a task. Call only by owner in unshared queues. |
646 |
> |
* |
647 |
> |
* @param task the task. Caller must ensure non-null. |
648 |
> |
* @param p if non-null, pool to signal if necessary |
649 |
> |
* @throw RejectedExecutionException if array cannot be resized |
650 |
> |
*/ |
651 |
> |
final void push(ForkJoinTask<?> task, ForkJoinPool p) { |
652 |
> |
ForkJoinTask<?>[] a; |
653 |
> |
int s = top, m, n; |
654 |
> |
if ((a = array) != null) { // ignore if queue removed |
655 |
> |
U.putOrderedObject |
656 |
> |
(a, (((m = a.length - 1) & s) << ASHIFT) + ABASE, task); |
657 |
> |
if ((n = (top = s + 1) - base) <= 2) { |
658 |
> |
if (p != null) |
659 |
> |
p.signalWork(); |
660 |
> |
} |
661 |
> |
else if (n >= m) |
662 |
> |
growArray(true); |
663 |
> |
} |
664 |
> |
} |
665 |
|
|
666 |
< |
/** |
667 |
< |
* The wakeup interval (in nanoseconds) for the oldest worker |
668 |
< |
* waiting for an event to invoke tryShutdownUnusedWorker to |
669 |
< |
* shrink the number of workers. The exact value does not matter |
670 |
< |
* too much. It must be short enough to release resources during |
671 |
< |
* sustained periods of idleness, but not so short that threads |
672 |
< |
* are continually re-created. |
673 |
< |
*/ |
674 |
< |
private static final long SHRINK_RATE_NANOS = |
675 |
< |
30L * 1000L * 1000L * 1000L; // 2 per minute |
666 |
> |
/** |
667 |
> |
* Pushes a task if lock is free and array is either big |
668 |
> |
* enough or can be resized to be big enough. |
669 |
> |
* |
670 |
> |
* @param task the task. Caller must ensure non-null. |
671 |
> |
* @return true if submitted |
672 |
> |
*/ |
673 |
> |
final boolean trySharedPush(ForkJoinTask<?> task) { |
674 |
> |
boolean submitted = false; |
675 |
> |
if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) { |
676 |
> |
ForkJoinTask<?>[] a = array; |
677 |
> |
int s = top; |
678 |
> |
try { |
679 |
> |
if ((a != null && a.length > s + 1 - base) || |
680 |
> |
(a = growArray(false)) != null) { // must presize |
681 |
> |
int j = (((a.length - 1) & s) << ASHIFT) + ABASE; |
682 |
> |
U.putObject(a, (long)j, task); // don't need "ordered" |
683 |
> |
top = s + 1; |
684 |
> |
submitted = true; |
685 |
> |
} |
686 |
> |
} finally { |
687 |
> |
runState = 0; // unlock |
688 |
> |
} |
689 |
> |
} |
690 |
> |
return submitted; |
691 |
> |
} |
692 |
|
|
693 |
< |
/** |
694 |
< |
* Absolute bound for parallelism level. Twice this number plus |
695 |
< |
* one (i.e., 0xfff) must fit into a 16bit field to enable |
696 |
< |
* word-packing for some counts and indices. |
697 |
< |
*/ |
698 |
< |
private static final int MAX_WORKERS = 0x7fff; |
693 |
> |
/** |
694 |
> |
* Takes next task, if one exists, in FIFO order. |
695 |
> |
*/ |
696 |
> |
final ForkJoinTask<?> poll() { |
697 |
> |
ForkJoinTask<?>[] a; int b; ForkJoinTask<?> t; |
698 |
> |
while ((b = base) - top < 0 && (a = array) != null) { |
699 |
> |
int j = (((a.length - 1) & b) << ASHIFT) + ABASE; |
700 |
> |
if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) != null && |
701 |
> |
base == b && |
702 |
> |
U.compareAndSwapObject(a, j, t, null)) { |
703 |
> |
base = b + 1; |
704 |
> |
return t; |
705 |
> |
} |
706 |
> |
} |
707 |
> |
return null; |
708 |
> |
} |
709 |
|
|
710 |
< |
/** |
711 |
< |
* Array holding all worker threads in the pool. Array size must |
712 |
< |
* be a power of two. Updates and replacements are protected by |
713 |
< |
* workerLock, but the array is always kept in a consistent enough |
714 |
< |
* state to be randomly accessed without locking by workers |
715 |
< |
* performing work-stealing, as well as other traversal-based |
716 |
< |
* methods in this class. All readers must tolerate that some |
717 |
< |
* array slots may be null. |
718 |
< |
*/ |
719 |
< |
volatile ForkJoinWorkerThread[] workers; |
710 |
> |
/** |
711 |
> |
* Takes next task, if one exists, in LIFO order. Call only |
712 |
> |
* by owner in unshared queues. (We do not have a shared |
713 |
> |
* version of this method because it is never needed.) |
714 |
> |
*/ |
715 |
> |
final ForkJoinTask<?> pop() { |
716 |
> |
ForkJoinTask<?> t; int m; |
717 |
> |
ForkJoinTask<?>[] a = array; |
718 |
> |
if (a != null && (m = a.length - 1) >= 0) { |
719 |
> |
for (int s; (s = top - 1) - base >= 0;) { |
720 |
> |
int j = ((m & s) << ASHIFT) + ABASE; |
721 |
> |
if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) == null) |
722 |
> |
break; |
723 |
> |
if (U.compareAndSwapObject(a, j, t, null)) { |
724 |
> |
top = s; |
725 |
> |
return t; |
726 |
> |
} |
727 |
> |
} |
728 |
> |
} |
729 |
> |
return null; |
730 |
> |
} |
731 |
|
|
732 |
< |
/** |
733 |
< |
* Queue for external submissions. |
734 |
< |
*/ |
735 |
< |
private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue; |
732 |
> |
/** |
733 |
> |
* Takes next task, if one exists, in order specified by mode. |
734 |
> |
*/ |
735 |
> |
final ForkJoinTask<?> nextLocalTask() { |
736 |
> |
return mode == 0 ? pop() : poll(); |
737 |
> |
} |
738 |
|
|
739 |
< |
/** |
740 |
< |
* Lock protecting updates to workers array. |
741 |
< |
*/ |
742 |
< |
private final ReentrantLock workerLock; |
739 |
> |
/** |
740 |
> |
* Returns next task, if one exists, in order specified by mode. |
741 |
> |
*/ |
742 |
> |
final ForkJoinTask<?> peek() { |
743 |
> |
ForkJoinTask<?>[] a = array; int m; |
744 |
> |
if (a == null || (m = a.length - 1) < 0) |
745 |
> |
return null; |
746 |
> |
int i = mode == 0 ? top - 1 : base; |
747 |
> |
int j = ((i & m) << ASHIFT) + ABASE; |
748 |
> |
return (ForkJoinTask<?>)U.getObjectVolatile(a, j); |
749 |
> |
} |
750 |
|
|
751 |
< |
/** |
752 |
< |
* Latch released upon termination. |
753 |
< |
*/ |
754 |
< |
private final Phaser termination; |
751 |
> |
/** |
752 |
> |
* Returns task at index b if b is current base of queue. |
753 |
> |
*/ |
754 |
> |
final ForkJoinTask<?> pollAt(int b) { |
755 |
> |
ForkJoinTask<?> t; ForkJoinTask<?>[] a; |
756 |
> |
if ((a = array) != null) { |
757 |
> |
int j = (((a.length - 1) & b) << ASHIFT) + ABASE; |
758 |
> |
if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) != null && |
759 |
> |
base == b && |
760 |
> |
U.compareAndSwapObject(a, j, t, null)) { |
761 |
> |
base = b + 1; |
762 |
> |
return t; |
763 |
> |
} |
764 |
> |
} |
765 |
> |
return null; |
766 |
> |
} |
767 |
|
|
768 |
< |
/** |
769 |
< |
* Creation factory for worker threads. |
770 |
< |
*/ |
771 |
< |
private final ForkJoinWorkerThreadFactory factory; |
768 |
> |
/** |
769 |
> |
* Pops the given task only if it is at the current top. |
770 |
> |
*/ |
771 |
> |
final boolean tryUnpush(ForkJoinTask<?> t) { |
772 |
> |
ForkJoinTask<?>[] a; int s; |
773 |
> |
if ((a = array) != null && (s = top) != base && |
774 |
> |
U.compareAndSwapObject |
775 |
> |
(a, (((a.length - 1) & --s) << ASHIFT) + ABASE, t, null)) { |
776 |
> |
top = s; |
777 |
> |
return true; |
778 |
> |
} |
779 |
> |
return false; |
780 |
> |
} |
781 |
|
|
782 |
< |
/** |
783 |
< |
* Sum of per-thread steal counts, updated only when threads are |
784 |
< |
* idle or terminating. |
785 |
< |
*/ |
786 |
< |
private volatile long stealCount; |
782 |
> |
/** |
783 |
> |
* Polls the given task only if it is at the current base. |
784 |
> |
*/ |
785 |
> |
final boolean pollFor(ForkJoinTask<?> task) { |
786 |
> |
ForkJoinTask<?>[] a; int b; |
787 |
> |
if ((b = base) - top < 0 && (a = array) != null) { |
788 |
> |
int j = (((a.length - 1) & b) << ASHIFT) + ABASE; |
789 |
> |
if (U.getObjectVolatile(a, j) == task && base == b && |
790 |
> |
U.compareAndSwapObject(a, j, task, null)) { |
791 |
> |
base = b + 1; |
792 |
> |
return true; |
793 |
> |
} |
794 |
> |
} |
795 |
> |
return false; |
796 |
> |
} |
797 |
|
|
798 |
< |
/** |
799 |
< |
* Encoded record of top of Treiber stack of threads waiting for |
800 |
< |
* events. The top 32 bits contain the count being waited for. The |
801 |
< |
* bottom 16 bits contains one plus the pool index of waiting |
802 |
< |
* worker thread. (Bits 16-31 are unused.) |
803 |
< |
*/ |
804 |
< |
private volatile long eventWaiters; |
798 |
> |
/** |
799 |
> |
* If present, removes from queue and executes the given task, or |
800 |
> |
* any other cancelled task. Returns (true) immediately on any CAS |
801 |
> |
* or consistency check failure so caller can retry. |
802 |
> |
* |
803 |
> |
* @return false if no progress can be made |
804 |
> |
*/ |
805 |
> |
final boolean tryRemoveAndExec(ForkJoinTask<?> task) { |
806 |
> |
boolean removed = false, empty = true, progress = true; |
807 |
> |
ForkJoinTask<?>[] a; int m, s, b, n; |
808 |
> |
if ((a = array) != null && (m = a.length - 1) >= 0 && |
809 |
> |
(n = (s = top) - (b = base)) > 0) { |
810 |
> |
for (ForkJoinTask<?> t;;) { // traverse from s to b |
811 |
> |
int j = ((--s & m) << ASHIFT) + ABASE; |
812 |
> |
t = (ForkJoinTask<?>)U.getObjectVolatile(a, j); |
813 |
> |
if (t == null) // inconsistent length |
814 |
> |
break; |
815 |
> |
else if (t == task) { |
816 |
> |
if (s + 1 == top) { // pop |
817 |
> |
if (!U.compareAndSwapObject(a, j, task, null)) |
818 |
> |
break; |
819 |
> |
top = s; |
820 |
> |
removed = true; |
821 |
> |
} |
822 |
> |
else if (base == b) // replace with proxy |
823 |
> |
removed = U.compareAndSwapObject(a, j, task, |
824 |
> |
new EmptyTask()); |
825 |
> |
break; |
826 |
> |
} |
827 |
> |
else if (t.status >= 0) |
828 |
> |
empty = false; |
829 |
> |
else if (s + 1 == top) { // pop and throw away |
830 |
> |
if (U.compareAndSwapObject(a, j, t, null)) |
831 |
> |
top = s; |
832 |
> |
break; |
833 |
> |
} |
834 |
> |
if (--n == 0) { |
835 |
> |
if (!empty && base == b) |
836 |
> |
progress = false; |
837 |
> |
break; |
838 |
> |
} |
839 |
> |
} |
840 |
> |
} |
841 |
> |
if (removed) |
842 |
> |
task.doExec(); |
843 |
> |
return progress; |
844 |
> |
} |
845 |
|
|
846 |
< |
private static final int EVENT_COUNT_SHIFT = 32; |
847 |
< |
private static final int WAITER_ID_MASK = (1 << 16) - 1; |
846 |
> |
/** |
847 |
> |
* Initializes or doubles the capacity of array. Call either |
848 |
> |
* by owner or with lock held -- it is OK for base, but not |
849 |
> |
* top, to move while resizings are in progress. |
850 |
> |
* |
851 |
> |
* @param rejectOnFailure if true, throw exception if capacity |
852 |
> |
* exceeded (relayed ultimately to user); else return null. |
853 |
> |
*/ |
854 |
> |
final ForkJoinTask<?>[] growArray(boolean rejectOnFailure) { |
855 |
> |
ForkJoinTask<?>[] oldA = array; |
856 |
> |
int size = oldA != null ? oldA.length << 1 : INITIAL_QUEUE_CAPACITY; |
857 |
> |
if (size <= MAXIMUM_QUEUE_CAPACITY) { |
858 |
> |
int oldMask, t, b; |
859 |
> |
ForkJoinTask<?>[] a = array = new ForkJoinTask<?>[size]; |
860 |
> |
if (oldA != null && (oldMask = oldA.length - 1) >= 0 && |
861 |
> |
(t = top) - (b = base) > 0) { |
862 |
> |
int mask = size - 1; |
863 |
> |
do { |
864 |
> |
ForkJoinTask<?> x; |
865 |
> |
int oldj = ((b & oldMask) << ASHIFT) + ABASE; |
866 |
> |
int j = ((b & mask) << ASHIFT) + ABASE; |
867 |
> |
x = (ForkJoinTask<?>)U.getObjectVolatile(oldA, oldj); |
868 |
> |
if (x != null && |
869 |
> |
U.compareAndSwapObject(oldA, oldj, x, null)) |
870 |
> |
U.putObjectVolatile(a, j, x); |
871 |
> |
} while (++b != t); |
872 |
> |
} |
873 |
> |
return a; |
874 |
> |
} |
875 |
> |
else if (!rejectOnFailure) |
876 |
> |
return null; |
877 |
> |
else |
878 |
> |
throw new RejectedExecutionException("Queue capacity exceeded"); |
879 |
> |
} |
880 |
|
|
881 |
< |
/** |
882 |
< |
* A counter for events that may wake up worker threads: |
883 |
< |
* - Submission of a new task to the pool |
884 |
< |
* - A worker pushing a task on an empty queue |
885 |
< |
* - termination |
886 |
< |
*/ |
887 |
< |
private volatile int eventCount; |
881 |
> |
/** |
882 |
> |
* Removes and cancels all known tasks, ignoring any exceptions. |
883 |
> |
*/ |
884 |
> |
final void cancelAll() { |
885 |
> |
ForkJoinTask.cancelIgnoringExceptions(currentJoin); |
886 |
> |
ForkJoinTask.cancelIgnoringExceptions(currentSteal); |
887 |
> |
for (ForkJoinTask<?> t; (t = poll()) != null; ) |
888 |
> |
ForkJoinTask.cancelIgnoringExceptions(t); |
889 |
> |
} |
890 |
|
|
891 |
< |
/** |
892 |
< |
* Encoded record of top of Treiber stack of spare threads waiting |
893 |
< |
* for resumption. The top 16 bits contain an arbitrary count to |
894 |
< |
* avoid ABA effects. The bottom 16bits contains one plus the pool |
895 |
< |
* index of waiting worker thread. |
896 |
< |
*/ |
897 |
< |
private volatile int spareWaiters; |
891 |
> |
/** |
892 |
> |
* Computes next value for random probes. Scans don't require |
893 |
> |
* a very high quality generator, but also not a crummy one. |
894 |
> |
* Marsaglia xor-shift is cheap and works well enough. Note: |
895 |
> |
* This is manually inlined in several usages in ForkJoinPool |
896 |
> |
* to avoid writes inside busy scan loops. |
897 |
> |
*/ |
898 |
> |
final int nextSeed() { |
899 |
> |
int r = seed; |
900 |
> |
r ^= r << 13; |
901 |
> |
r ^= r >>> 17; |
902 |
> |
return seed = r ^= r << 5; |
903 |
> |
} |
904 |
|
|
905 |
< |
private static final int SPARE_COUNT_SHIFT = 16; |
519 |
< |
private static final int SPARE_ID_MASK = (1 << 16) - 1; |
905 |
> |
// Execution methods |
906 |
|
|
907 |
< |
/** |
908 |
< |
* Lifecycle control. The low word contains the number of workers |
909 |
< |
* that are (probably) executing tasks. This value is atomically |
910 |
< |
* incremented before a worker gets a task to run, and decremented |
911 |
< |
* when a worker has no tasks and cannot find any. Bits 16-18 |
912 |
< |
* contain runLevel value. When all are zero, the pool is |
913 |
< |
* running. Level transitions are monotonic (running -> shutdown |
914 |
< |
* -> terminating -> terminated) so each transition adds a bit. |
915 |
< |
* These are bundled together to ensure consistent read for |
916 |
< |
* termination checks (i.e., that runLevel is at least SHUTDOWN |
531 |
< |
* and active threads is zero). |
532 |
< |
* |
533 |
< |
* Notes: Most direct CASes are dependent on these bitfield |
534 |
< |
* positions. Also, this field is non-private to enable direct |
535 |
< |
* performance-sensitive CASes in ForkJoinWorkerThread. |
536 |
< |
*/ |
537 |
< |
volatile int runState; |
907 |
> |
/** |
908 |
> |
* Removes and runs tasks until empty, using local mode |
909 |
> |
* ordering. |
910 |
> |
*/ |
911 |
> |
final void runLocalTasks() { |
912 |
> |
if (base - top < 0) { |
913 |
> |
for (ForkJoinTask<?> t; (t = nextLocalTask()) != null; ) |
914 |
> |
t.doExec(); |
915 |
> |
} |
916 |
> |
} |
917 |
|
|
918 |
< |
// Note: The order among run level values matters. |
919 |
< |
private static final int RUNLEVEL_SHIFT = 16; |
920 |
< |
private static final int SHUTDOWN = 1 << RUNLEVEL_SHIFT; |
921 |
< |
private static final int TERMINATING = 1 << (RUNLEVEL_SHIFT + 1); |
922 |
< |
private static final int TERMINATED = 1 << (RUNLEVEL_SHIFT + 2); |
923 |
< |
private static final int ACTIVE_COUNT_MASK = (1 << RUNLEVEL_SHIFT) - 1; |
918 |
> |
/** |
919 |
> |
* Executes a top-level task and any local tasks remaining |
920 |
> |
* after execution. |
921 |
> |
* |
922 |
> |
* @return true unless terminating |
923 |
> |
*/ |
924 |
> |
final boolean runTask(ForkJoinTask<?> t) { |
925 |
> |
boolean alive = true; |
926 |
> |
if (t != null) { |
927 |
> |
currentSteal = t; |
928 |
> |
t.doExec(); |
929 |
> |
runLocalTasks(); |
930 |
> |
++nsteals; |
931 |
> |
currentSteal = null; |
932 |
> |
} |
933 |
> |
else if (runState < 0) // terminating |
934 |
> |
alive = false; |
935 |
> |
return alive; |
936 |
> |
} |
937 |
|
|
938 |
< |
/** |
939 |
< |
* Holds number of total (i.e., created and not yet terminated) |
940 |
< |
* and running (i.e., not blocked on joins or other managed sync) |
941 |
< |
* threads, packed together to ensure consistent snapshot when |
942 |
< |
* making decisions about creating and suspending spare |
943 |
< |
* threads. Updated only by CAS. Note that adding a new worker |
944 |
< |
* requires incrementing both counts, since workers start off in |
945 |
< |
* running state. |
946 |
< |
*/ |
947 |
< |
private volatile int workerCounts; |
938 |
> |
/** |
939 |
> |
* Executes a non-top-level (stolen) task. |
940 |
> |
*/ |
941 |
> |
final void runSubtask(ForkJoinTask<?> t) { |
942 |
> |
if (t != null) { |
943 |
> |
ForkJoinTask<?> ps = currentSteal; |
944 |
> |
currentSteal = t; |
945 |
> |
t.doExec(); |
946 |
> |
currentSteal = ps; |
947 |
> |
} |
948 |
> |
} |
949 |
|
|
950 |
< |
private static final int TOTAL_COUNT_SHIFT = 16; |
951 |
< |
private static final int RUNNING_COUNT_MASK = (1 << TOTAL_COUNT_SHIFT) - 1; |
952 |
< |
private static final int ONE_RUNNING = 1; |
953 |
< |
private static final int ONE_TOTAL = 1 << TOTAL_COUNT_SHIFT; |
950 |
> |
/** |
951 |
> |
* Returns true if owned and not known to be blocked. |
952 |
> |
*/ |
953 |
> |
final boolean isApparentlyUnblocked() { |
954 |
> |
Thread wt; Thread.State s; |
955 |
> |
return (eventCount >= 0 && |
956 |
> |
(wt = owner) != null && |
957 |
> |
(s = wt.getState()) != Thread.State.BLOCKED && |
958 |
> |
s != Thread.State.WAITING && |
959 |
> |
s != Thread.State.TIMED_WAITING); |
960 |
> |
} |
961 |
|
|
962 |
< |
/** |
963 |
< |
* The target parallelism level. |
964 |
< |
* Accessed directly by ForkJoinWorkerThreads. |
965 |
< |
*/ |
966 |
< |
final int parallelism; |
962 |
> |
/** |
963 |
> |
* If this owned and is not already interrupted, try to |
964 |
> |
* interrupt and/or unpark, ignoring exceptions. |
965 |
> |
*/ |
966 |
> |
final void interruptOwner() { |
967 |
> |
Thread wt, p; |
968 |
> |
if ((wt = owner) != null && !wt.isInterrupted()) { |
969 |
> |
try { |
970 |
> |
wt.interrupt(); |
971 |
> |
} catch (SecurityException ignore) { |
972 |
> |
} |
973 |
> |
} |
974 |
> |
if ((p = parker) != null) |
975 |
> |
U.unpark(p); |
976 |
> |
} |
977 |
|
|
978 |
< |
/** |
979 |
< |
* True if use local fifo, not default lifo, for local polling |
980 |
< |
* Read by, and replicated by ForkJoinWorkerThreads |
981 |
< |
*/ |
982 |
< |
final boolean locallyFifo; |
978 |
> |
// Unsafe mechanics |
979 |
> |
private static final sun.misc.Unsafe U; |
980 |
> |
private static final long RUNSTATE; |
981 |
> |
private static final int ABASE; |
982 |
> |
private static final int ASHIFT; |
983 |
> |
static { |
984 |
> |
int s; |
985 |
> |
try { |
986 |
> |
U = getUnsafe(); |
987 |
> |
Class<?> k = WorkQueue.class; |
988 |
> |
Class<?> ak = ForkJoinTask[].class; |
989 |
> |
RUNSTATE = U.objectFieldOffset |
990 |
> |
(k.getDeclaredField("runState")); |
991 |
> |
ABASE = U.arrayBaseOffset(ak); |
992 |
> |
s = U.arrayIndexScale(ak); |
993 |
> |
} catch (Exception e) { |
994 |
> |
throw new Error(e); |
995 |
> |
} |
996 |
> |
if ((s & (s-1)) != 0) |
997 |
> |
throw new Error("data type scale not a power of two"); |
998 |
> |
ASHIFT = 31 - Integer.numberOfLeadingZeros(s); |
999 |
> |
} |
1000 |
> |
} |
1001 |
|
|
1002 |
|
/** |
1003 |
< |
* The uncaught exception handler used when any worker abruptly |
1004 |
< |
* terminates. |
1003 |
> |
* Per-thread records for threads that submit to pools. Currently |
1004 |
> |
* holds only psuedo-random seed / index that is used to choose |
1005 |
> |
* submission queues in method doSubmit. In the future, this may |
1006 |
> |
* also incorporate a means to implement different task rejection |
1007 |
> |
* and resubmission policies. |
1008 |
|
*/ |
1009 |
< |
private final Thread.UncaughtExceptionHandler ueh; |
1009 |
> |
static final class Submitter { |
1010 |
> |
int seed; |
1011 |
> |
Submitter() { seed = hashId(Thread.currentThread().getId()); } |
1012 |
> |
} |
1013 |
|
|
1014 |
< |
/** |
1015 |
< |
* Pool number, just for assigning useful names to worker threads |
1016 |
< |
*/ |
1017 |
< |
private final int poolNumber; |
1014 |
> |
/** ThreadLocal class for Submitters */ |
1015 |
> |
static final class ThreadSubmitter extends ThreadLocal<Submitter> { |
1016 |
> |
public Submitter initialValue() { return new Submitter(); } |
1017 |
> |
} |
1018 |
|
|
1019 |
< |
// Utilities for CASing fields. Note that most of these |
586 |
< |
// are usually manually inlined by callers |
1019 |
> |
// static fields (initialized in static initializer below) |
1020 |
|
|
1021 |
|
/** |
1022 |
< |
* Increments running count part of workerCounts. |
1022 |
> |
* Creates a new ForkJoinWorkerThread. This factory is used unless |
1023 |
> |
* overridden in ForkJoinPool constructors. |
1024 |
|
*/ |
1025 |
< |
final void incrementRunningCount() { |
1026 |
< |
int c; |
593 |
< |
do {} while (!UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
594 |
< |
c = workerCounts, |
595 |
< |
c + ONE_RUNNING)); |
596 |
< |
} |
1025 |
> |
public static final ForkJoinWorkerThreadFactory |
1026 |
> |
defaultForkJoinWorkerThreadFactory; |
1027 |
|
|
1028 |
|
/** |
1029 |
< |
* Tries to increment running count part of workerCounts. |
1029 |
> |
* Generator for assigning sequence numbers as pool names. |
1030 |
|
*/ |
1031 |
< |
final boolean tryIncrementRunningCount() { |
602 |
< |
int c; |
603 |
< |
return UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
604 |
< |
c = workerCounts, |
605 |
< |
c + ONE_RUNNING); |
606 |
< |
} |
1031 |
> |
private static final AtomicInteger poolNumberGenerator; |
1032 |
|
|
1033 |
|
/** |
1034 |
< |
* Tries to decrement running count unless already zero. |
1034 |
> |
* Permission required for callers of methods that may start or |
1035 |
> |
* kill threads. |
1036 |
|
*/ |
1037 |
< |
final boolean tryDecrementRunningCount() { |
612 |
< |
int wc = workerCounts; |
613 |
< |
if ((wc & RUNNING_COUNT_MASK) == 0) |
614 |
< |
return false; |
615 |
< |
return UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
616 |
< |
wc, wc - ONE_RUNNING); |
617 |
< |
} |
1037 |
> |
private static final RuntimePermission modifyThreadPermission; |
1038 |
|
|
1039 |
|
/** |
1040 |
< |
* Forces decrement of encoded workerCounts, awaiting nonzero if |
1041 |
< |
* (rarely) necessary when other count updates lag. |
1042 |
< |
* |
623 |
< |
* @param dr -- either zero or ONE_RUNNING |
624 |
< |
* @param dt -- either zero or ONE_TOTAL |
1040 |
> |
* Per-thread submission bookeeping. Shared across all pools |
1041 |
> |
* to reduce ThreadLocal pollution and because random motion |
1042 |
> |
* to avoid contention in one pool is likely to hold for others. |
1043 |
|
*/ |
1044 |
< |
private void decrementWorkerCounts(int dr, int dt) { |
1045 |
< |
for (;;) { |
1046 |
< |
int wc = workerCounts; |
629 |
< |
if ((wc & RUNNING_COUNT_MASK) - dr < 0 || |
630 |
< |
(wc >>> TOTAL_COUNT_SHIFT) - dt < 0) { |
631 |
< |
if ((runState & TERMINATED) != 0) |
632 |
< |
return; // lagging termination on a backout |
633 |
< |
Thread.yield(); |
634 |
< |
} |
635 |
< |
if (UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
636 |
< |
wc, wc - (dr + dt))) |
637 |
< |
return; |
638 |
< |
} |
639 |
< |
} |
1044 |
> |
private static final ThreadSubmitter submitters; |
1045 |
> |
|
1046 |
> |
// static constants |
1047 |
|
|
1048 |
|
/** |
1049 |
< |
* Tries decrementing active count; fails on contention. |
1050 |
< |
* Called when workers cannot find tasks to run. |
1049 |
> |
* The wakeup interval (in nanoseconds) for a worker waiting for a |
1050 |
> |
* task when the pool is quiescent to instead try to shrink the |
1051 |
> |
* number of workers. The exact value does not matter too |
1052 |
> |
* much. It must be short enough to release resources during |
1053 |
> |
* sustained periods of idleness, but not so short that threads |
1054 |
> |
* are continually re-created. |
1055 |
|
*/ |
1056 |
< |
final boolean tryDecrementActiveCount() { |
1057 |
< |
int c; |
647 |
< |
return UNSAFE.compareAndSwapInt(this, runStateOffset, |
648 |
< |
c = runState, c - 1); |
649 |
< |
} |
1056 |
> |
private static final long SHRINK_RATE = |
1057 |
> |
4L * 1000L * 1000L * 1000L; // 4 seconds |
1058 |
|
|
1059 |
|
/** |
1060 |
< |
* Advances to at least the given level. Returns true if not |
1061 |
< |
* already in at least the given level. |
1060 |
> |
* The timeout value for attempted shrinkage, includes |
1061 |
> |
* some slop to cope with system timer imprecision. |
1062 |
|
*/ |
1063 |
< |
private boolean advanceRunLevel(int level) { |
1064 |
< |
for (;;) { |
1065 |
< |
int s = runState; |
1066 |
< |
if ((s & level) != 0) |
1067 |
< |
return false; |
1068 |
< |
if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, s | level)) |
1069 |
< |
return true; |
1063 |
> |
private static final long SHRINK_TIMEOUT = SHRINK_RATE - (SHRINK_RATE / 10); |
1064 |
> |
|
1065 |
> |
/** |
1066 |
> |
* The maximum stolen->joining link depth allowed in tryHelpStealer. |
1067 |
> |
* Depths for legitimate chains are unbounded, but we use a fixed |
1068 |
> |
* constant to avoid (otherwise unchecked) cycles and to bound |
1069 |
> |
* staleness of traversal parameters at the expense of sometimes |
1070 |
> |
* blocking when we could be helping. |
1071 |
> |
*/ |
1072 |
> |
private static final int MAX_HELP_DEPTH = 16; |
1073 |
> |
|
1074 |
> |
/** |
1075 |
> |
* Bits and masks for control variables |
1076 |
> |
* |
1077 |
> |
* Field ctl is a long packed with: |
1078 |
> |
* AC: Number of active running workers minus target parallelism (16 bits) |
1079 |
> |
* TC: Number of total workers minus target parallelism (16 bits) |
1080 |
> |
* ST: true if pool is terminating (1 bit) |
1081 |
> |
* EC: the wait count of top waiting thread (15 bits) |
1082 |
> |
* ID: poolIndex of top of Treiber stack of waiters (16 bits) |
1083 |
> |
* |
1084 |
> |
* When convenient, we can extract the upper 32 bits of counts and |
1085 |
> |
* the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e = |
1086 |
> |
* (int)ctl. The ec field is never accessed alone, but always |
1087 |
> |
* together with id and st. The offsets of counts by the target |
1088 |
> |
* parallelism and the positionings of fields makes it possible to |
1089 |
> |
* perform the most common checks via sign tests of fields: When |
1090 |
> |
* ac is negative, there are not enough active workers, when tc is |
1091 |
> |
* negative, there are not enough total workers, and when e is |
1092 |
> |
* negative, the pool is terminating. To deal with these possibly |
1093 |
> |
* negative fields, we use casts in and out of "short" and/or |
1094 |
> |
* signed shifts to maintain signedness. |
1095 |
> |
* |
1096 |
> |
* When a thread is queued (inactivated), its eventCount field is |
1097 |
> |
* set negative, which is the only way to tell if a worker is |
1098 |
> |
* prevented from executing tasks, even though it must continue to |
1099 |
> |
* scan for them to avoid queuing races. Note however that |
1100 |
> |
* eventCount updates lag releases so usage requires care. |
1101 |
> |
* |
1102 |
> |
* Field runState is an int packed with: |
1103 |
> |
* SHUTDOWN: true if shutdown is enabled (1 bit) |
1104 |
> |
* SEQ: a sequence number updated upon (de)registering workers (15 bits) |
1105 |
> |
* MASK: mask (power of 2 - 1) covering all registered poolIndexes (16 bits) |
1106 |
> |
* |
1107 |
> |
* The combination of mask and sequence number enables simple |
1108 |
> |
* consistency checks: Staleness of read-only operations on the |
1109 |
> |
* workQueues array can be checked by comparing runState before vs |
1110 |
> |
* after the reads. The low 16 bits (i.e, anding with SMASK) hold |
1111 |
> |
* the smallest power of two covering all indices, minus |
1112 |
> |
* one. |
1113 |
> |
*/ |
1114 |
> |
|
1115 |
> |
// bit positions/shifts for fields |
1116 |
> |
private static final int AC_SHIFT = 48; |
1117 |
> |
private static final int TC_SHIFT = 32; |
1118 |
> |
private static final int ST_SHIFT = 31; |
1119 |
> |
private static final int EC_SHIFT = 16; |
1120 |
> |
|
1121 |
> |
// bounds |
1122 |
> |
private static final int POOL_MAX = 0x7fff; // max #workers - 1 |
1123 |
> |
private static final int SMASK = 0xffff; // short bits |
1124 |
> |
private static final int SQMASK = 0xfffe; // even short bits |
1125 |
> |
private static final int SHORT_SIGN = 1 << 15; |
1126 |
> |
private static final int INT_SIGN = 1 << 31; |
1127 |
> |
|
1128 |
> |
// masks |
1129 |
> |
private static final long STOP_BIT = 0x0001L << ST_SHIFT; |
1130 |
> |
private static final long AC_MASK = ((long)SMASK) << AC_SHIFT; |
1131 |
> |
private static final long TC_MASK = ((long)SMASK) << TC_SHIFT; |
1132 |
> |
|
1133 |
> |
// units for incrementing and decrementing |
1134 |
> |
private static final long TC_UNIT = 1L << TC_SHIFT; |
1135 |
> |
private static final long AC_UNIT = 1L << AC_SHIFT; |
1136 |
> |
|
1137 |
> |
// masks and units for dealing with u = (int)(ctl >>> 32) |
1138 |
> |
private static final int UAC_SHIFT = AC_SHIFT - 32; |
1139 |
> |
private static final int UTC_SHIFT = TC_SHIFT - 32; |
1140 |
> |
private static final int UAC_MASK = SMASK << UAC_SHIFT; |
1141 |
> |
private static final int UTC_MASK = SMASK << UTC_SHIFT; |
1142 |
> |
private static final int UAC_UNIT = 1 << UAC_SHIFT; |
1143 |
> |
private static final int UTC_UNIT = 1 << UTC_SHIFT; |
1144 |
> |
|
1145 |
> |
// masks and units for dealing with e = (int)ctl |
1146 |
> |
private static final int E_MASK = 0x7fffffff; // no STOP_BIT |
1147 |
> |
private static final int E_SEQ = 1 << EC_SHIFT; |
1148 |
> |
|
1149 |
> |
// runState bits |
1150 |
> |
private static final int SHUTDOWN = 1 << 31; |
1151 |
> |
private static final int RS_SEQ = 1 << 16; |
1152 |
> |
private static final int RS_SEQ_MASK = 0x7fff0000; |
1153 |
> |
|
1154 |
> |
// access mode for WorkQueue |
1155 |
> |
static final int LIFO_QUEUE = 0; |
1156 |
> |
static final int FIFO_QUEUE = 1; |
1157 |
> |
static final int SHARED_QUEUE = -1; |
1158 |
> |
|
1159 |
> |
// Instance fields |
1160 |
> |
|
1161 |
> |
/* |
1162 |
> |
* Field layout order in this class tends to matter more than one |
1163 |
> |
* would like. Runtime layout order is only loosely related to |
1164 |
> |
* declaration order and may differ across JVMs, but the following |
1165 |
> |
* empirically works OK on current JVMs. |
1166 |
> |
*/ |
1167 |
> |
|
1168 |
> |
volatile long ctl; // main pool control |
1169 |
> |
final int parallelism; // parallelism level |
1170 |
> |
final int localMode; // per-worker scheduling mode |
1171 |
> |
int growHints; // for expanding indices/ranges |
1172 |
> |
volatile int runState; // shutdown status, seq, and mask |
1173 |
> |
WorkQueue[] workQueues; // main registry |
1174 |
> |
final Mutex lock; // for registration |
1175 |
> |
final Condition termination; // for awaitTermination |
1176 |
> |
final ForkJoinWorkerThreadFactory factory; // factory for new workers |
1177 |
> |
final Thread.UncaughtExceptionHandler ueh; // per-worker UEH |
1178 |
> |
final AtomicLong stealCount; // collect counts when terminated |
1179 |
> |
final AtomicInteger nextWorkerNumber; // to create worker name string |
1180 |
> |
final String workerNamePrefix; // to create worker name string |
1181 |
> |
|
1182 |
> |
// Creating, registering, deregistering and running workers |
1183 |
> |
|
1184 |
> |
/** |
1185 |
> |
* Tries to create and start a worker |
1186 |
> |
*/ |
1187 |
> |
private void addWorker() { |
1188 |
> |
Throwable ex = null; |
1189 |
> |
ForkJoinWorkerThread wt = null; |
1190 |
> |
try { |
1191 |
> |
if ((wt = factory.newThread(this)) != null) { |
1192 |
> |
wt.start(); |
1193 |
> |
return; |
1194 |
> |
} |
1195 |
> |
} catch (Throwable e) { |
1196 |
> |
ex = e; |
1197 |
|
} |
1198 |
+ |
deregisterWorker(wt, ex); // adjust counts etc on failure |
1199 |
|
} |
1200 |
|
|
665 |
– |
// workers array maintenance |
666 |
– |
|
1201 |
|
/** |
1202 |
< |
* Records and returns a workers array index for new worker. |
1202 |
> |
* Callback from ForkJoinWorkerThread constructor to assign a |
1203 |
> |
* public name. This must be separate from registerWorker because |
1204 |
> |
* it is called during the "super" constructor call in |
1205 |
> |
* ForkJoinWorkerThread. |
1206 |
|
*/ |
1207 |
< |
private int recordWorker(ForkJoinWorkerThread w) { |
1208 |
< |
// Try using slot totalCount-1. If not available, scan and/or resize |
1209 |
< |
int k = (workerCounts >>> TOTAL_COUNT_SHIFT) - 1; |
673 |
< |
final ReentrantLock lock = this.workerLock; |
674 |
< |
lock.lock(); |
675 |
< |
try { |
676 |
< |
ForkJoinWorkerThread[] ws = workers; |
677 |
< |
int n = ws.length; |
678 |
< |
if (k < 0 || k >= n || ws[k] != null) { |
679 |
< |
for (k = 0; k < n && ws[k] != null; ++k) |
680 |
< |
; |
681 |
< |
if (k == n) |
682 |
< |
ws = workers = Arrays.copyOf(ws, n << 1); |
683 |
< |
} |
684 |
< |
ws[k] = w; |
685 |
< |
int c = eventCount; // advance event count to ensure visibility |
686 |
< |
UNSAFE.compareAndSwapInt(this, eventCountOffset, c, c+1); |
687 |
< |
} finally { |
688 |
< |
lock.unlock(); |
689 |
< |
} |
690 |
< |
return k; |
1207 |
> |
final String nextWorkerName() { |
1208 |
> |
return workerNamePrefix.concat |
1209 |
> |
(Integer.toString(nextWorkerNumber.addAndGet(1))); |
1210 |
|
} |
1211 |
|
|
1212 |
|
/** |
1213 |
< |
* Nulls out record of worker in workers array. |
1213 |
> |
* Callback from ForkJoinWorkerThread constructor to establish and |
1214 |
> |
* record its WorkQueue. |
1215 |
> |
* |
1216 |
> |
* @param wt the worker thread |
1217 |
|
*/ |
1218 |
< |
private void forgetWorker(ForkJoinWorkerThread w) { |
1219 |
< |
int idx = w.poolIndex; |
1220 |
< |
// Locking helps method recordWorker avoid unnecessary expansion |
699 |
< |
final ReentrantLock lock = this.workerLock; |
1218 |
> |
final void registerWorker(ForkJoinWorkerThread wt) { |
1219 |
> |
WorkQueue w = wt.workQueue; |
1220 |
> |
Mutex lock = this.lock; |
1221 |
|
lock.lock(); |
1222 |
|
try { |
1223 |
< |
ForkJoinWorkerThread[] ws = workers; |
1224 |
< |
if (idx >= 0 && idx < ws.length && ws[idx] == w) // verify |
1225 |
< |
ws[idx] = null; |
1223 |
> |
int g = growHints, k = g & SMASK; |
1224 |
> |
WorkQueue[] ws = workQueues; |
1225 |
> |
if (ws != null) { // ignore on shutdown |
1226 |
> |
int n = ws.length; |
1227 |
> |
if ((k & 1) == 0 || k >= n || ws[k] != null) { |
1228 |
> |
for (k = 1; k < n && ws[k] != null; k += 2) |
1229 |
> |
; // workers are at odd indices |
1230 |
> |
if (k >= n) // resize |
1231 |
> |
workQueues = ws = Arrays.copyOf(ws, n << 1); |
1232 |
> |
} |
1233 |
> |
w.eventCount = w.poolIndex = k; // establish before recording |
1234 |
> |
ws[k] = w; |
1235 |
> |
growHints = (g & ~SMASK) | ((k + 2) & SMASK); |
1236 |
> |
int rs = runState; |
1237 |
> |
int m = rs & SMASK; // recalculate runState mask |
1238 |
> |
if (k > m) |
1239 |
> |
m = (m << 1) + 1; |
1240 |
> |
runState = (rs & SHUTDOWN) | ((rs + RS_SEQ) & RS_SEQ_MASK) | m; |
1241 |
> |
} |
1242 |
|
} finally { |
1243 |
|
lock.unlock(); |
1244 |
|
} |
1245 |
|
} |
1246 |
|
|
1247 |
|
/** |
1248 |
< |
* Final callback from terminating worker. Removes record of |
1248 |
> |
* Final callback from terminating worker, as well as upon failure |
1249 |
> |
* to construct or start a worker in addWorker. Removes record of |
1250 |
|
* worker from array, and adjusts counts. If pool is shutting |
1251 |
|
* down, tries to complete termination. |
1252 |
|
* |
1253 |
< |
* @param w the worker |
1253 |
> |
* @param wt the worker thread or null if addWorker failed |
1254 |
> |
* @param ex the exception causing failure, or null if none |
1255 |
|
*/ |
1256 |
< |
final void workerTerminated(ForkJoinWorkerThread w) { |
1257 |
< |
forgetWorker(w); |
1258 |
< |
decrementWorkerCounts(w.isTrimmed() ? 0 : ONE_RUNNING, ONE_TOTAL); |
1259 |
< |
while (w.stealCount != 0) // collect final count |
1260 |
< |
tryAccumulateStealCount(w); |
1261 |
< |
tryTerminate(false); |
1262 |
< |
} |
1263 |
< |
|
1264 |
< |
// Waiting for and signalling events |
1265 |
< |
|
1266 |
< |
/** |
1267 |
< |
* Releases workers blocked on a count not equal to current count. |
1268 |
< |
* Normally called after precheck that eventWaiters isn't zero to |
1269 |
< |
* avoid wasted array checks. Gives up upon a change in count or |
1270 |
< |
* upon releasing two workers, letting others take over. |
1271 |
< |
*/ |
733 |
< |
private void releaseEventWaiters() { |
734 |
< |
ForkJoinWorkerThread[] ws = workers; |
735 |
< |
int n = ws.length; |
736 |
< |
long h = eventWaiters; |
737 |
< |
int ec = eventCount; |
738 |
< |
boolean releasedOne = false; |
739 |
< |
ForkJoinWorkerThread w; int id; |
740 |
< |
while ((id = (((int)h) & WAITER_ID_MASK) - 1) >= 0 && |
741 |
< |
(int)(h >>> EVENT_COUNT_SHIFT) != ec && |
742 |
< |
id < n && (w = ws[id]) != null) { |
743 |
< |
if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset, |
744 |
< |
h, w.nextWaiter)) { |
745 |
< |
LockSupport.unpark(w); |
746 |
< |
if (releasedOne) // exit on second release |
747 |
< |
break; |
748 |
< |
releasedOne = true; |
1256 |
> |
final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) { |
1257 |
> |
WorkQueue w = null; |
1258 |
> |
if (wt != null && (w = wt.workQueue) != null) { |
1259 |
> |
w.runState = -1; // ensure runState is set |
1260 |
> |
stealCount.getAndAdd(w.totalSteals + w.nsteals); |
1261 |
> |
int idx = w.poolIndex; |
1262 |
> |
Mutex lock = this.lock; |
1263 |
> |
lock.lock(); |
1264 |
> |
try { // remove record from array |
1265 |
> |
WorkQueue[] ws = workQueues; |
1266 |
> |
if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w) { |
1267 |
> |
ws[idx] = null; |
1268 |
> |
growHints = (growHints & ~SMASK) | idx; |
1269 |
> |
} |
1270 |
> |
} finally { |
1271 |
> |
lock.unlock(); |
1272 |
|
} |
750 |
– |
if (eventCount != ec) |
751 |
– |
break; |
752 |
– |
h = eventWaiters; |
1273 |
|
} |
1274 |
+ |
|
1275 |
+ |
long c; // adjust ctl counts |
1276 |
+ |
do {} while (!U.compareAndSwapLong |
1277 |
+ |
(this, CTL, c = ctl, (((c - AC_UNIT) & AC_MASK) | |
1278 |
+ |
((c - TC_UNIT) & TC_MASK) | |
1279 |
+ |
(c & ~(AC_MASK|TC_MASK))))); |
1280 |
+ |
|
1281 |
+ |
if (!tryTerminate(false, false) && w != null) { |
1282 |
+ |
w.cancelAll(); // cancel remaining tasks |
1283 |
+ |
if (w.array != null) // suppress signal if never ran |
1284 |
+ |
signalWork(); // wake up or create replacement |
1285 |
+ |
if (ex == null) // help clean refs on way out |
1286 |
+ |
ForkJoinTask.helpExpungeStaleExceptions(); |
1287 |
+ |
} |
1288 |
+ |
|
1289 |
+ |
if (ex != null) // rethrow |
1290 |
+ |
U.throwException(ex); |
1291 |
|
} |
1292 |
|
|
1293 |
|
/** |
1294 |
< |
* Tries to advance eventCount and releases waiters. Called only |
758 |
< |
* from workers. |
1294 |
> |
* Top-level runloop for workers, called by ForkJoinWorkerThread.run. |
1295 |
|
*/ |
1296 |
< |
final void signalWork() { |
1297 |
< |
int c; // try to increment event count -- CAS failure OK |
1298 |
< |
UNSAFE.compareAndSwapInt(this, eventCountOffset, c = eventCount, c+1); |
1299 |
< |
if (eventWaiters != 0L) |
1300 |
< |
releaseEventWaiters(); |
765 |
< |
} |
1296 |
> |
final void runWorker(ForkJoinWorkerThread wt) { |
1297 |
> |
// Initialize queue array and seed in this thread |
1298 |
> |
WorkQueue w = wt.workQueue; |
1299 |
> |
w.growArray(false); |
1300 |
> |
w.seed = hashId(Thread.currentThread().getId()); |
1301 |
|
|
1302 |
< |
/** |
768 |
< |
* Adds the given worker to event queue and blocks until |
769 |
< |
* terminating or event count advances from the given value |
770 |
< |
* |
771 |
< |
* @param w the calling worker thread |
772 |
< |
* @param ec the count |
773 |
< |
*/ |
774 |
< |
private void eventSync(ForkJoinWorkerThread w, int ec) { |
775 |
< |
long nh = (((long)ec) << EVENT_COUNT_SHIFT) | ((long)(w.poolIndex+1)); |
776 |
< |
long h; |
777 |
< |
while ((runState < SHUTDOWN || !tryTerminate(false)) && |
778 |
< |
(((int)(h = eventWaiters) & WAITER_ID_MASK) == 0 || |
779 |
< |
(int)(h >>> EVENT_COUNT_SHIFT) == ec) && |
780 |
< |
eventCount == ec) { |
781 |
< |
if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset, |
782 |
< |
w.nextWaiter = h, nh)) { |
783 |
< |
awaitEvent(w, ec); |
784 |
< |
break; |
785 |
< |
} |
786 |
< |
} |
1302 |
> |
do {} while (w.runTask(scan(w))); |
1303 |
|
} |
1304 |
|
|
1305 |
+ |
// Submissions |
1306 |
+ |
|
1307 |
|
/** |
1308 |
< |
* Blocks the given worker (that has already been entered as an |
1309 |
< |
* event waiter) until terminating or event count advances from |
1310 |
< |
* the given value. The oldest (first) waiter uses a timed wait to |
1311 |
< |
* occasionally one-by-one shrink the number of workers (to a |
1312 |
< |
* minimum of one) if the pool has not been used for extended |
1313 |
< |
* periods. |
1314 |
< |
* |
1315 |
< |
* @param w the calling worker thread |
1316 |
< |
* @param ec the count |
1317 |
< |
*/ |
1318 |
< |
private void awaitEvent(ForkJoinWorkerThread w, int ec) { |
1319 |
< |
while (eventCount == ec) { |
1320 |
< |
if (tryAccumulateStealCount(w)) { // transfer while idle |
1321 |
< |
boolean untimed = (w.nextWaiter != 0L || |
1322 |
< |
(workerCounts & RUNNING_COUNT_MASK) <= 1); |
1323 |
< |
long startTime = untimed ? 0 : System.nanoTime(); |
1324 |
< |
Thread.interrupted(); // clear/ignore interrupt |
1325 |
< |
if (w.isTerminating() || eventCount != ec) |
1326 |
< |
break; // recheck after clear |
1327 |
< |
if (untimed) |
1328 |
< |
LockSupport.park(w); |
1329 |
< |
else { |
1330 |
< |
LockSupport.parkNanos(w, SHRINK_RATE_NANOS); |
1331 |
< |
if (eventCount != ec || w.isTerminating()) |
1332 |
< |
break; |
1333 |
< |
if (System.nanoTime() - startTime >= SHRINK_RATE_NANOS) |
1334 |
< |
tryShutdownUnusedWorker(ec); |
1308 |
> |
* Unless shutting down, adds the given task to a submission queue |
1309 |
> |
* at submitter's current queue index (modulo submission |
1310 |
> |
* range). If no queue exists at the index, one is created unless |
1311 |
> |
* pool lock is busy. If the queue and/or lock are busy, another |
1312 |
> |
* index is randomly chosen. The mask in growHints controls the |
1313 |
> |
* effective index range of queues considered. The mask is |
1314 |
> |
* expanded, up to the current workerQueue mask, upon any detected |
1315 |
> |
* contention but otherwise remains small to avoid needlessly |
1316 |
> |
* creating queues when there is no contention. |
1317 |
> |
*/ |
1318 |
> |
private void doSubmit(ForkJoinTask<?> task) { |
1319 |
> |
if (task == null) |
1320 |
> |
throw new NullPointerException(); |
1321 |
> |
Submitter s = submitters.get(); |
1322 |
> |
for (int r = s.seed, m = growHints >>> 16;;) { |
1323 |
> |
WorkQueue[] ws; WorkQueue q; Mutex lk; |
1324 |
> |
int k = r & m & SQMASK; // use only even indices |
1325 |
> |
if (runState < 0 || (ws = workQueues) == null || ws.length <= k) |
1326 |
> |
throw new RejectedExecutionException(); // shutting down |
1327 |
> |
if ((q = ws[k]) == null && (lk = lock).tryAcquire(0)) { |
1328 |
> |
try { // try to create new queue |
1329 |
> |
if (ws == workQueues && (q = ws[k]) == null) { |
1330 |
> |
int rs; // update runState seq |
1331 |
> |
ws[k] = q = new WorkQueue(null, SHARED_QUEUE); |
1332 |
> |
runState = (((rs = runState) & SHUTDOWN) | |
1333 |
> |
((rs + RS_SEQ) & ~SHUTDOWN)); |
1334 |
> |
} |
1335 |
> |
} finally { |
1336 |
> |
lk.unlock(); |
1337 |
> |
} |
1338 |
> |
} |
1339 |
> |
if (q != null) { |
1340 |
> |
if (q.trySharedPush(task)) { |
1341 |
> |
signalWork(); |
1342 |
> |
return; |
1343 |
> |
} |
1344 |
> |
else if (m < parallelism - 1 && m < (runState & SMASK)) { |
1345 |
> |
Mutex lock = this.lock; |
1346 |
> |
lock.lock(); // block until lock free |
1347 |
> |
int g = growHints; |
1348 |
> |
if (g >>> 16 == m) // expand range |
1349 |
> |
growHints = (((m << 1) + 1) << 16) | (g & SMASK); |
1350 |
> |
lock.unlock(); // no need for try/finally |
1351 |
|
} |
1352 |
+ |
else if ((r & m) == 0) |
1353 |
+ |
Thread.yield(); // occasionally yield if busy |
1354 |
+ |
} |
1355 |
+ |
if (m == (m = growHints >>> 16)) { |
1356 |
+ |
r ^= r << 13; // update seed unless new range |
1357 |
+ |
r ^= r >>> 17; // same xorshift as WorkQueues |
1358 |
+ |
s.seed = r ^= r << 5; |
1359 |
|
} |
1360 |
|
} |
1361 |
|
} |
1362 |
|
|
1363 |
< |
// Maintaining parallelism |
1363 |
> |
// Maintaining ctl counts |
1364 |
|
|
1365 |
|
/** |
1366 |
< |
* Pushes worker onto the spare stack. |
1366 |
> |
* Increments active count; mainly called upon return from blocking. |
1367 |
|
*/ |
1368 |
< |
final void pushSpare(ForkJoinWorkerThread w) { |
1369 |
< |
int ns = (++w.spareCount << SPARE_COUNT_SHIFT) | (w.poolIndex + 1); |
1370 |
< |
do {} while (!UNSAFE.compareAndSwapInt(this, spareWaitersOffset, |
830 |
< |
w.nextSpare = spareWaiters,ns)); |
1368 |
> |
final void incrementActiveCount() { |
1369 |
> |
long c; |
1370 |
> |
do {} while (!U.compareAndSwapLong(this, CTL, c = ctl, c + AC_UNIT)); |
1371 |
|
} |
1372 |
|
|
1373 |
|
/** |
1374 |
< |
* Tries (once) to resume a spare if the number of running |
835 |
< |
* threads is less than target. |
1374 |
> |
* Tries to activate or create a worker if too few are active. |
1375 |
|
*/ |
1376 |
< |
private void tryResumeSpare() { |
1377 |
< |
int sw, id; |
1378 |
< |
ForkJoinWorkerThread[] ws = workers; |
1379 |
< |
int n = ws.length; |
1380 |
< |
ForkJoinWorkerThread w; |
1381 |
< |
if ((sw = spareWaiters) != 0 && |
1382 |
< |
(id = (sw & SPARE_ID_MASK) - 1) >= 0 && |
1383 |
< |
id < n && (w = ws[id]) != null && |
1384 |
< |
(runState >= TERMINATING || |
1385 |
< |
(workerCounts & RUNNING_COUNT_MASK) < parallelism) && |
1386 |
< |
spareWaiters == sw && |
1387 |
< |
UNSAFE.compareAndSwapInt(this, spareWaitersOffset, |
1388 |
< |
sw, w.nextSpare)) { |
1389 |
< |
int c; // increment running count before resume |
1390 |
< |
do {} while (!UNSAFE.compareAndSwapInt |
1391 |
< |
(this, workerCountsOffset, |
1392 |
< |
c = workerCounts, c + ONE_RUNNING)); |
1393 |
< |
if (w.tryUnsuspend()) |
1394 |
< |
LockSupport.unpark(w); |
1395 |
< |
else // back out if w was shutdown |
1396 |
< |
decrementWorkerCounts(ONE_RUNNING, 0); |
1376 |
> |
final void signalWork() { |
1377 |
> |
long c; int u; |
1378 |
> |
while ((u = (int)((c = ctl) >>> 32)) < 0) { // too few active |
1379 |
> |
WorkQueue[] ws = workQueues; int e, i; WorkQueue w; Thread p; |
1380 |
> |
if ((e = (int)c) > 0) { // at least one waiting |
1381 |
> |
if (ws != null && (i = e & SMASK) < ws.length && |
1382 |
> |
(w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) { |
1383 |
> |
long nc = (((long)(w.nextWait & E_MASK)) | |
1384 |
> |
((long)(u + UAC_UNIT) << 32)); |
1385 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
1386 |
> |
w.eventCount = (e + E_SEQ) & E_MASK; |
1387 |
> |
if ((p = w.parker) != null) |
1388 |
> |
U.unpark(p); // activate and release |
1389 |
> |
break; |
1390 |
> |
} |
1391 |
> |
} |
1392 |
> |
else |
1393 |
> |
break; |
1394 |
> |
} |
1395 |
> |
else if (e == 0 && (u & SHORT_SIGN) != 0) { // too few total |
1396 |
> |
long nc = (long)(((u + UTC_UNIT) & UTC_MASK) | |
1397 |
> |
((u + UAC_UNIT) & UAC_MASK)) << 32; |
1398 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
1399 |
> |
addWorker(); |
1400 |
> |
break; |
1401 |
> |
} |
1402 |
> |
} |
1403 |
> |
else |
1404 |
> |
break; |
1405 |
|
} |
1406 |
|
} |
1407 |
|
|
1408 |
|
/** |
1409 |
< |
* Tries to increase the number of running workers if below target |
1410 |
< |
* parallelism: If a spare exists tries to resume it via |
1411 |
< |
* tryResumeSpare. Otherwise, if not enough total workers or all |
1412 |
< |
* existing workers are busy, adds a new worker. In all cases also |
1413 |
< |
* helps wake up releasable workers waiting for work. |
1414 |
< |
*/ |
1415 |
< |
private void helpMaintainParallelism() { |
1416 |
< |
int pc = parallelism; |
1417 |
< |
int wc, rs, tc; |
1418 |
< |
while (((wc = workerCounts) & RUNNING_COUNT_MASK) < pc && |
1419 |
< |
(rs = runState) < TERMINATING) { |
1420 |
< |
if (spareWaiters != 0) |
1421 |
< |
tryResumeSpare(); |
1422 |
< |
else if ((tc = wc >>> TOTAL_COUNT_SHIFT) >= MAX_WORKERS || |
1423 |
< |
(tc >= pc && (rs & ACTIVE_COUNT_MASK) != tc)) |
1424 |
< |
break; // enough total |
1425 |
< |
else if (runState == rs && workerCounts == wc && |
1426 |
< |
UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc, |
1427 |
< |
wc + (ONE_RUNNING|ONE_TOTAL))) { |
1428 |
< |
ForkJoinWorkerThread w = null; |
1429 |
< |
Throwable fail = null; |
1430 |
< |
try { |
884 |
< |
w = factory.newThread(this); |
885 |
< |
} catch (Throwable ex) { |
886 |
< |
fail = ex; |
887 |
< |
} |
888 |
< |
if (w == null) { // null or exceptional factory return |
889 |
< |
decrementWorkerCounts(ONE_RUNNING, ONE_TOTAL); |
890 |
< |
tryTerminate(false); // handle failure during shutdown |
891 |
< |
// If originating from an external caller, |
892 |
< |
// propagate exception, else ignore |
893 |
< |
if (fail != null && runState < TERMINATING && |
894 |
< |
!(Thread.currentThread() instanceof |
895 |
< |
ForkJoinWorkerThread)) |
896 |
< |
UNSAFE.throwException(fail); |
897 |
< |
break; |
1409 |
> |
* Tries to decrement active count (sometimes implicitly) and |
1410 |
> |
* possibly release or create a compensating worker in preparation |
1411 |
> |
* for blocking. Fails on contention or termination. |
1412 |
> |
* |
1413 |
> |
* @return true if the caller can block, else should recheck and retry |
1414 |
> |
*/ |
1415 |
> |
final boolean tryCompensate() { |
1416 |
> |
WorkQueue w; Thread p; |
1417 |
> |
int pc = parallelism, e, u, ac, tc, i; |
1418 |
> |
long c = ctl; |
1419 |
> |
WorkQueue[] ws = workQueues; |
1420 |
> |
if ((e = (int)c) >= 0) { |
1421 |
> |
if ((ac = ((u = (int)(c >>> 32)) >> UAC_SHIFT)) <= 0 && |
1422 |
> |
e != 0 && ws != null && (i = e & SMASK) < ws.length && |
1423 |
> |
(w = ws[i]) != null) { |
1424 |
> |
long nc = (long)(w.nextWait & E_MASK) | (c & (AC_MASK|TC_MASK)); |
1425 |
> |
if (w.eventCount == (e | INT_SIGN) && |
1426 |
> |
U.compareAndSwapLong(this, CTL, c, nc)) { |
1427 |
> |
w.eventCount = (e + E_SEQ) & E_MASK; |
1428 |
> |
if ((p = w.parker) != null) |
1429 |
> |
U.unpark(p); |
1430 |
> |
return true; // release an idle worker |
1431 |
|
} |
899 |
– |
w.start(recordWorker(w), ueh); |
900 |
– |
if ((workerCounts >>> TOTAL_COUNT_SHIFT) >= pc) |
901 |
– |
break; // add at most one unless total below target |
902 |
– |
} |
903 |
– |
} |
904 |
– |
if (eventWaiters != 0L) |
905 |
– |
releaseEventWaiters(); |
906 |
– |
} |
907 |
– |
|
908 |
– |
/** |
909 |
– |
* Callback from the oldest waiter in awaitEvent waking up after a |
910 |
– |
* period of non-use. If all workers are idle, tries (once) to |
911 |
– |
* shutdown an event waiter or a spare, if one exists. Note that |
912 |
– |
* we don't need CAS or locks here because the method is called |
913 |
– |
* only from one thread occasionally waking (and even misfires are |
914 |
– |
* OK). Note that until the shutdown worker fully terminates, |
915 |
– |
* workerCounts will overestimate total count, which is tolerable. |
916 |
– |
* |
917 |
– |
* @param ec the event count waited on by caller (to abort |
918 |
– |
* attempt if count has since changed). |
919 |
– |
*/ |
920 |
– |
private void tryShutdownUnusedWorker(int ec) { |
921 |
– |
if (runState == 0 && eventCount == ec) { // only trigger if all idle |
922 |
– |
ForkJoinWorkerThread[] ws = workers; |
923 |
– |
int n = ws.length; |
924 |
– |
ForkJoinWorkerThread w = null; |
925 |
– |
boolean shutdown = false; |
926 |
– |
int sw; |
927 |
– |
long h; |
928 |
– |
if ((sw = spareWaiters) != 0) { // prefer killing spares |
929 |
– |
int id = (sw & SPARE_ID_MASK) - 1; |
930 |
– |
if (id >= 0 && id < n && (w = ws[id]) != null && |
931 |
– |
UNSAFE.compareAndSwapInt(this, spareWaitersOffset, |
932 |
– |
sw, w.nextSpare)) |
933 |
– |
shutdown = true; |
934 |
– |
} |
935 |
– |
else if ((h = eventWaiters) != 0L) { |
936 |
– |
long nh; |
937 |
– |
int id = (((int)h) & WAITER_ID_MASK) - 1; |
938 |
– |
if (id >= 0 && id < n && (w = ws[id]) != null && |
939 |
– |
(nh = w.nextWaiter) != 0L && // keep at least one worker |
940 |
– |
UNSAFE.compareAndSwapLong(this, eventWaitersOffset, h, nh)) |
941 |
– |
shutdown = true; |
942 |
– |
} |
943 |
– |
if (w != null && shutdown) { |
944 |
– |
w.shutdown(); |
945 |
– |
LockSupport.unpark(w); |
946 |
– |
} |
947 |
– |
} |
948 |
– |
releaseEventWaiters(); // in case of interference |
949 |
– |
} |
950 |
– |
|
951 |
– |
/** |
952 |
– |
* Callback from workers invoked upon each top-level action (i.e., |
953 |
– |
* stealing a task or taking a submission and running it). |
954 |
– |
* Performs one or more of the following: |
955 |
– |
* |
956 |
– |
* 1. If the worker is active and either did not run a task |
957 |
– |
* or there are too many workers, try to set its active status |
958 |
– |
* to inactive and update activeCount. On contention, we may |
959 |
– |
* try again in this or a subsequent call. |
960 |
– |
* |
961 |
– |
* 2. If not enough total workers, help create some. |
962 |
– |
* |
963 |
– |
* 3. If there are too many running workers, suspend this worker |
964 |
– |
* (first forcing inactive if necessary). If it is not needed, |
965 |
– |
* it may be shutdown while suspended (via |
966 |
– |
* tryShutdownUnusedWorker). Otherwise, upon resume it |
967 |
– |
* rechecks running thread count and need for event sync. |
968 |
– |
* |
969 |
– |
* 4. If worker did not run a task, await the next task event via |
970 |
– |
* eventSync if necessary (first forcing inactivation), upon |
971 |
– |
* which the worker may be shutdown via |
972 |
– |
* tryShutdownUnusedWorker. Otherwise, help release any |
973 |
– |
* existing event waiters that are now releasable, |
974 |
– |
* |
975 |
– |
* @param w the worker |
976 |
– |
* @param ran true if worker ran a task since last call to this method |
977 |
– |
*/ |
978 |
– |
final void preStep(ForkJoinWorkerThread w, boolean ran) { |
979 |
– |
int wec = w.lastEventCount; |
980 |
– |
boolean active = w.active; |
981 |
– |
boolean inactivate = false; |
982 |
– |
int pc = parallelism; |
983 |
– |
while (w.runState == 0) { |
984 |
– |
int rs = runState; |
985 |
– |
if (rs >= TERMINATING) { // propagate shutdown |
986 |
– |
w.shutdown(); |
987 |
– |
break; |
1432 |
|
} |
1433 |
< |
if ((inactivate || (active && (rs & ACTIVE_COUNT_MASK) >= pc)) && |
1434 |
< |
UNSAFE.compareAndSwapInt(this, runStateOffset, rs, --rs)) { |
1435 |
< |
inactivate = active = w.active = false; |
1436 |
< |
if (rs == SHUTDOWN) { // all inactive and shut down |
1437 |
< |
tryTerminate(false); |
1438 |
< |
continue; |
1439 |
< |
} |
1440 |
< |
} |
1441 |
< |
int wc = workerCounts; // try to suspend as spare |
1442 |
< |
if ((wc & RUNNING_COUNT_MASK) > pc) { |
999 |
< |
if (!(inactivate |= active) && // must inactivate to suspend |
1000 |
< |
workerCounts == wc && |
1001 |
< |
UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
1002 |
< |
wc, wc - ONE_RUNNING)) |
1003 |
< |
w.suspendAsSpare(); |
1004 |
< |
} |
1005 |
< |
else if ((wc >>> TOTAL_COUNT_SHIFT) < pc) |
1006 |
< |
helpMaintainParallelism(); // not enough workers |
1007 |
< |
else if (ran) |
1008 |
< |
break; |
1009 |
< |
else { |
1010 |
< |
long h = eventWaiters; |
1011 |
< |
int ec = eventCount; |
1012 |
< |
if (h != 0L && (int)(h >>> EVENT_COUNT_SHIFT) != ec) |
1013 |
< |
releaseEventWaiters(); // release others before waiting |
1014 |
< |
else if (ec != wec) { |
1015 |
< |
w.lastEventCount = ec; // no need to wait |
1016 |
< |
break; |
1433 |
> |
else if ((tc = (short)(u >>> UTC_SHIFT)) >= 0 && ac + pc > 1) { |
1434 |
> |
long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK); |
1435 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) |
1436 |
> |
return true; // no compensation needed |
1437 |
> |
} |
1438 |
> |
else if (tc + pc < POOL_MAX) { |
1439 |
> |
long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK); |
1440 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
1441 |
> |
addWorker(); |
1442 |
> |
return true; // create replacement |
1443 |
|
} |
1018 |
– |
else if (!(inactivate |= active)) |
1019 |
– |
eventSync(w, wec); // must inactivate before sync |
1444 |
|
} |
1445 |
|
} |
1446 |
+ |
return false; |
1447 |
|
} |
1448 |
|
|
1449 |
+ |
// Scanning for tasks |
1450 |
+ |
|
1451 |
|
/** |
1452 |
< |
* Helps and/or blocks awaiting join of the given task. |
1453 |
< |
* See above for explanation. |
1454 |
< |
* |
1455 |
< |
* @param joinMe the task to join |
1456 |
< |
* @param worker the current worker thread |
1457 |
< |
* @param timed true if wait should time out |
1458 |
< |
* @param nanos timeout value if timed |
1459 |
< |
*/ |
1460 |
< |
final void awaitJoin(ForkJoinTask<?> joinMe, ForkJoinWorkerThread worker, |
1461 |
< |
boolean timed, long nanos) { |
1462 |
< |
long startTime = timed? System.nanoTime() : 0L; |
1463 |
< |
int retries = 2 + (parallelism >> 2); // #helpJoins before blocking |
1464 |
< |
boolean running = true; // false when count decremented |
1465 |
< |
while (joinMe.status >= 0) { |
1466 |
< |
if (runState >= TERMINATING) { |
1467 |
< |
joinMe.cancelIgnoringExceptions(); |
1468 |
< |
break; |
1452 |
> |
* Scans for and, if found, returns one task, else possibly |
1453 |
> |
* inactivates the worker. This method operates on single reads of |
1454 |
> |
* volatile state and is designed to be re-invoked continuously in |
1455 |
> |
* part because it returns upon detecting inconsistencies, |
1456 |
> |
* contention, or state changes that indicate possible success on |
1457 |
> |
* re-invocation. |
1458 |
> |
* |
1459 |
> |
* The scan searches for tasks across queues, randomly selecting |
1460 |
> |
* the first #queues probes, favoring steals over submissions |
1461 |
> |
* (by exploiting even/odd indexing), and then performing a |
1462 |
> |
* circular sweep of all queues. The scan terminates upon either |
1463 |
> |
* finding a non-empty queue, or completing a full sweep. If the |
1464 |
> |
* worker is not inactivated, it takes and returns a task from |
1465 |
> |
* this queue. On failure to find a task, we take one of the |
1466 |
> |
* following actions, after which the caller will retry calling |
1467 |
> |
* this method unless terminated. |
1468 |
> |
* |
1469 |
> |
* * If pool is terminating, terminate the worker. |
1470 |
> |
* |
1471 |
> |
* * If not a complete sweep, try to release a waiting worker. If |
1472 |
> |
* the scan terminated because the worker is inactivated, then the |
1473 |
> |
* released worker will often be the calling worker, and it can |
1474 |
> |
* succeed obtaining a task on the next call. Or maybe it is |
1475 |
> |
* another worker, but with same net effect. Releasing in other |
1476 |
> |
* cases as well ensures that we have enough workers running. |
1477 |
> |
* |
1478 |
> |
* * If the caller has run a task since the last empty scan, |
1479 |
> |
* return (to allow rescan) if other workers are not also yet |
1480 |
> |
* enqueued. Field WorkQueue.rescans counts down on each scan to |
1481 |
> |
* ensure eventual inactivation and blocking. |
1482 |
> |
* |
1483 |
> |
* * If not already enqueued, try to inactivate and enqueue the |
1484 |
> |
* worker on wait queue. |
1485 |
> |
* |
1486 |
> |
* * If already enqueued and none of the above apply, either park |
1487 |
> |
* awaiting signal, or if this is the most recent waiter and pool |
1488 |
> |
* is quiescent, relay to idleAwaitWork to check for termination |
1489 |
> |
* and possibly shrink pool. |
1490 |
> |
* |
1491 |
> |
* @param w the worker (via its WorkQueue) |
1492 |
> |
* @return a task or null of none found |
1493 |
> |
*/ |
1494 |
> |
private final ForkJoinTask<?> scan(WorkQueue w) { |
1495 |
> |
boolean swept = false; // true after full empty scan |
1496 |
> |
WorkQueue[] ws; // volatile read order matters |
1497 |
> |
int r = w.seed, ec = w.eventCount; // ec is negative if inactive |
1498 |
> |
int rs = runState, m = rs & SMASK; |
1499 |
> |
if ((ws = workQueues) != null && ws.length > m) { // consistency check |
1500 |
> |
for (int k = 0, j = -1 - m; ; ++j) { |
1501 |
> |
WorkQueue q; int b; |
1502 |
> |
if (j < 0) { // random probes while j negative |
1503 |
> |
r ^= r << 13; r ^= r >>> 17; k = (r ^= r << 5) | (j & 1); |
1504 |
> |
} // worker (not submit) for odd j |
1505 |
> |
else // cyclic scan when j >= 0 |
1506 |
> |
k += 7; // step 7 reduces array packing bias |
1507 |
> |
if ((q = ws[k & m]) != null && (b = q.base) - q.top < 0) { |
1508 |
> |
ForkJoinTask<?> t = (ec >= 0) ? q.pollAt(b) : null; |
1509 |
> |
w.seed = r; // save seed for next scan |
1510 |
> |
if (t != null) |
1511 |
> |
return t; |
1512 |
> |
break; |
1513 |
> |
} |
1514 |
> |
else if (j - m > m) { |
1515 |
> |
if (rs == runState) // staleness check |
1516 |
> |
swept = true; |
1517 |
> |
break; |
1518 |
> |
} |
1519 |
|
} |
1520 |
< |
running = worker.helpJoinTask(joinMe, running); |
1521 |
< |
if (joinMe.status < 0) |
1522 |
< |
break; |
1523 |
< |
if (retries > 0) { |
1524 |
< |
--retries; |
1525 |
< |
continue; |
1526 |
< |
} |
1527 |
< |
int wc = workerCounts; |
1528 |
< |
if ((wc & RUNNING_COUNT_MASK) != 0) { |
1529 |
< |
if (running) { |
1530 |
< |
if (!UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
1531 |
< |
wc, wc - ONE_RUNNING)) |
1532 |
< |
continue; |
1533 |
< |
running = false; |
1534 |
< |
} |
1058 |
< |
long h = eventWaiters; |
1059 |
< |
if (h != 0L && (int)(h >>> EVENT_COUNT_SHIFT) != eventCount) |
1060 |
< |
releaseEventWaiters(); |
1061 |
< |
if ((workerCounts & RUNNING_COUNT_MASK) != 0) { |
1062 |
< |
long ms; int ns; |
1063 |
< |
if (!timed) { |
1064 |
< |
ms = JOIN_TIMEOUT_MILLIS; |
1065 |
< |
ns = 0; |
1066 |
< |
} |
1067 |
< |
else { // at most JOIN_TIMEOUT_MILLIS per wait |
1068 |
< |
long nt = nanos - (System.nanoTime() - startTime); |
1069 |
< |
if (nt <= 0L) |
1070 |
< |
break; |
1071 |
< |
ms = nt / 1000000; |
1072 |
< |
if (ms > JOIN_TIMEOUT_MILLIS) { |
1073 |
< |
ms = JOIN_TIMEOUT_MILLIS; |
1074 |
< |
ns = 0; |
1075 |
< |
} |
1076 |
< |
else |
1077 |
< |
ns = (int) (nt % 1000000); |
1520 |
> |
|
1521 |
> |
// Decode ctl on empty scan |
1522 |
> |
long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns; |
1523 |
> |
if (e < 0) // pool is terminating |
1524 |
> |
w.runState = -1; |
1525 |
> |
else if (!swept) { // try to release a waiter |
1526 |
> |
WorkQueue v; Thread p; |
1527 |
> |
if (e > 0 && a < 0 && (v = ws[e & m]) != null && |
1528 |
> |
v.eventCount == (e | INT_SIGN)) { |
1529 |
> |
long nc = ((long)(v.nextWait & E_MASK) | |
1530 |
> |
((c + AC_UNIT) & (AC_MASK|TC_MASK))); |
1531 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
1532 |
> |
v.eventCount = (e + E_SEQ) & E_MASK; |
1533 |
> |
if ((p = v.parker) != null) |
1534 |
> |
U.unpark(p); |
1535 |
|
} |
1079 |
– |
joinMe.internalAwaitDone(ms, ns); |
1536 |
|
} |
1081 |
– |
if (joinMe.status < 0) |
1082 |
– |
break; |
1537 |
|
} |
1538 |
< |
helpMaintainParallelism(); |
1538 |
> |
else if ((nr = w.rescans) > 0) { // continue rescanning |
1539 |
> |
int ac = a + parallelism; |
1540 |
> |
if (((w.rescans = (ac < nr) ? ac : nr - 1) & 3) == 0 && |
1541 |
> |
w.eventCount == ec) |
1542 |
> |
Thread.yield(); // occasionally yield |
1543 |
> |
} |
1544 |
> |
else if (ec >= 0) { // try to enqueue |
1545 |
> |
long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK)); |
1546 |
> |
w.nextWait = e; |
1547 |
> |
w.eventCount = ec | INT_SIGN;// mark as inactive |
1548 |
> |
if (!U.compareAndSwapLong(this, CTL, c, nc)) |
1549 |
> |
w.eventCount = ec; // unmark on CAS failure |
1550 |
> |
else if ((ns = w.nsteals) != 0) { |
1551 |
> |
w.nsteals = 0; // set rescans if ran task |
1552 |
> |
w.rescans = a + parallelism; |
1553 |
> |
w.totalSteals += ns; |
1554 |
> |
} |
1555 |
> |
} |
1556 |
> |
else{ // already queued |
1557 |
> |
if (parallelism == -a) |
1558 |
> |
idleAwaitWork(w); // quiescent |
1559 |
> |
if (w.eventCount == ec) { |
1560 |
> |
Thread.interrupted(); // clear status |
1561 |
> |
ForkJoinWorkerThread wt = w.owner; |
1562 |
> |
U.putObject(wt, PARKBLOCKER, this); |
1563 |
> |
w.parker = wt; // emulate LockSupport.park |
1564 |
> |
if (w.eventCount == ec) // recheck |
1565 |
> |
U.park(false, 0L); // block |
1566 |
> |
w.parker = null; |
1567 |
> |
U.putObject(wt, PARKBLOCKER, null); |
1568 |
> |
} |
1569 |
> |
} |
1570 |
|
} |
1571 |
< |
if (!running) { |
1572 |
< |
int c; |
1573 |
< |
do {} while (!UNSAFE.compareAndSwapInt |
1574 |
< |
(this, workerCountsOffset, |
1575 |
< |
c = workerCounts, c + ONE_RUNNING)); |
1571 |
> |
return null; |
1572 |
> |
} |
1573 |
> |
|
1574 |
> |
/** |
1575 |
> |
* If inactivating worker w has caused pool to become quiescent, |
1576 |
> |
* checks for pool termination, and, so long as this is not the |
1577 |
> |
* only worker, waits for event for up to SHRINK_RATE nanosecs. |
1578 |
> |
* On timeout, if ctl has not changed, terminates the worker, |
1579 |
> |
* which will in turn wake up another worker to possibly repeat |
1580 |
> |
* this process. |
1581 |
> |
* |
1582 |
> |
* @param w the calling worker |
1583 |
> |
*/ |
1584 |
> |
private void idleAwaitWork(WorkQueue w) { |
1585 |
> |
long c; int nw, ec; |
1586 |
> |
if (!tryTerminate(false, false) && |
1587 |
> |
(int)((c = ctl) >> AC_SHIFT) + parallelism == 0 && |
1588 |
> |
(ec = w.eventCount) == ((int)c | INT_SIGN) && |
1589 |
> |
(nw = w.nextWait) != 0) { |
1590 |
> |
long nc = ((long)(nw & E_MASK) | // ctl to restore on timeout |
1591 |
> |
((c + AC_UNIT) & AC_MASK) | (c & TC_MASK)); |
1592 |
> |
ForkJoinWorkerThread wt = w.owner; |
1593 |
> |
while (ctl == c) { |
1594 |
> |
long startTime = System.nanoTime(); |
1595 |
> |
Thread.interrupted(); // timed variant of version in scan() |
1596 |
> |
U.putObject(wt, PARKBLOCKER, this); |
1597 |
> |
w.parker = wt; |
1598 |
> |
if (ctl == c) |
1599 |
> |
U.park(false, SHRINK_RATE); |
1600 |
> |
w.parker = null; |
1601 |
> |
U.putObject(wt, PARKBLOCKER, null); |
1602 |
> |
if (ctl != c) |
1603 |
> |
break; |
1604 |
> |
if (System.nanoTime() - startTime >= SHRINK_TIMEOUT && |
1605 |
> |
U.compareAndSwapLong(this, CTL, c, nc)) { |
1606 |
> |
w.eventCount = (ec + E_SEQ) | E_MASK; |
1607 |
> |
w.runState = -1; // shrink |
1608 |
> |
break; |
1609 |
> |
} |
1610 |
> |
} |
1611 |
|
} |
1612 |
|
} |
1613 |
|
|
1614 |
|
/** |
1615 |
< |
* Same idea as awaitJoin, but no helping, retries, or timeouts. |
1616 |
< |
*/ |
1617 |
< |
final void awaitBlocker(ManagedBlocker blocker) |
1618 |
< |
throws InterruptedException { |
1619 |
< |
while (!blocker.isReleasable()) { |
1620 |
< |
int wc = workerCounts; |
1621 |
< |
if ((wc & RUNNING_COUNT_MASK) == 0) |
1622 |
< |
helpMaintainParallelism(); |
1623 |
< |
else if (UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
1624 |
< |
wc, wc - ONE_RUNNING)) { |
1625 |
< |
try { |
1626 |
< |
while (!blocker.isReleasable()) { |
1627 |
< |
long h = eventWaiters; |
1628 |
< |
if (h != 0L && |
1629 |
< |
(int)(h >>> EVENT_COUNT_SHIFT) != eventCount) |
1630 |
< |
releaseEventWaiters(); |
1631 |
< |
else if ((workerCounts & RUNNING_COUNT_MASK) == 0 && |
1632 |
< |
runState < TERMINATING) |
1633 |
< |
helpMaintainParallelism(); |
1634 |
< |
else if (blocker.block()) |
1615 |
> |
* Tries to locate and execute tasks for a stealer of the given |
1616 |
> |
* task, or in turn one of its stealers, Traces currentSteal -> |
1617 |
> |
* currentJoin links looking for a thread working on a descendant |
1618 |
> |
* of the given task and with a non-empty queue to steal back and |
1619 |
> |
* execute tasks from. The first call to this method upon a |
1620 |
> |
* waiting join will often entail scanning/search, (which is OK |
1621 |
> |
* because the joiner has nothing better to do), but this method |
1622 |
> |
* leaves hints in workers to speed up subsequent calls. The |
1623 |
> |
* implementation is very branchy to cope with potential |
1624 |
> |
* inconsistencies or loops encountering chains that are stale, |
1625 |
> |
* unknown, or of length greater than MAX_HELP_DEPTH links. All |
1626 |
> |
* of these cases are dealt with by just retrying by caller. |
1627 |
> |
* |
1628 |
> |
* @param joiner the joining worker |
1629 |
> |
* @param task the task to join |
1630 |
> |
* @return true if found or ran a task (and so is immediately retryable) |
1631 |
> |
*/ |
1632 |
> |
final boolean tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) { |
1633 |
> |
ForkJoinTask<?> subtask; // current target |
1634 |
> |
boolean progress = false; |
1635 |
> |
int depth = 0; // current chain depth |
1636 |
> |
int m = runState & SMASK; |
1637 |
> |
WorkQueue[] ws = workQueues; |
1638 |
> |
|
1639 |
> |
if (ws != null && ws.length > m && (subtask = task).status >= 0) { |
1640 |
> |
outer:for (WorkQueue j = joiner;;) { |
1641 |
> |
// Try to find the stealer of subtask, by first using hint |
1642 |
> |
WorkQueue stealer = null; |
1643 |
> |
WorkQueue v = ws[j.stealHint & m]; |
1644 |
> |
if (v != null && v.currentSteal == subtask) |
1645 |
> |
stealer = v; |
1646 |
> |
else { |
1647 |
> |
for (int i = 1; i <= m; i += 2) { |
1648 |
> |
if ((v = ws[i]) != null && v.currentSteal == subtask) { |
1649 |
> |
stealer = v; |
1650 |
> |
j.stealHint = i; // save hint |
1651 |
|
break; |
1652 |
+ |
} |
1653 |
+ |
} |
1654 |
+ |
if (stealer == null) |
1655 |
+ |
break; |
1656 |
+ |
} |
1657 |
+ |
|
1658 |
+ |
for (WorkQueue q = stealer;;) { // Try to help stealer |
1659 |
+ |
ForkJoinTask<?> t; int b; |
1660 |
+ |
if (task.status < 0) |
1661 |
+ |
break outer; |
1662 |
+ |
if ((b = q.base) - q.top < 0) { |
1663 |
+ |
progress = true; |
1664 |
+ |
if (subtask.status < 0) |
1665 |
+ |
break outer; // stale |
1666 |
+ |
if ((t = q.pollAt(b)) != null) { |
1667 |
+ |
stealer.stealHint = joiner.poolIndex; |
1668 |
+ |
joiner.runSubtask(t); |
1669 |
+ |
} |
1670 |
+ |
} |
1671 |
+ |
else { // empty - try to descend to find stealer's stealer |
1672 |
+ |
ForkJoinTask<?> next = stealer.currentJoin; |
1673 |
+ |
if (++depth == MAX_HELP_DEPTH || subtask.status < 0 || |
1674 |
+ |
next == null || next == subtask) |
1675 |
+ |
break outer; // max depth, stale, dead-end, cyclic |
1676 |
+ |
subtask = next; |
1677 |
+ |
j = stealer; |
1678 |
+ |
break; |
1679 |
|
} |
1117 |
– |
} finally { |
1118 |
– |
int c; |
1119 |
– |
do {} while (!UNSAFE.compareAndSwapInt |
1120 |
– |
(this, workerCountsOffset, |
1121 |
– |
c = workerCounts, c + ONE_RUNNING)); |
1680 |
|
} |
1123 |
– |
break; |
1681 |
|
} |
1682 |
|
} |
1683 |
+ |
return progress; |
1684 |
|
} |
1685 |
|
|
1686 |
|
/** |
1687 |
< |
* Possibly initiates and/or completes termination. |
1687 |
> |
* If task is at base of some steal queue, steals and executes it. |
1688 |
|
* |
1689 |
< |
* @param now if true, unconditionally terminate, else only |
1690 |
< |
* if shutdown and empty queue and no active workers |
1133 |
< |
* @return true if now terminating or terminated |
1689 |
> |
* @param joiner the joining worker |
1690 |
> |
* @param task the task |
1691 |
|
*/ |
1692 |
< |
private boolean tryTerminate(boolean now) { |
1693 |
< |
if (now) |
1694 |
< |
advanceRunLevel(SHUTDOWN); // ensure at least SHUTDOWN |
1695 |
< |
else if (runState < SHUTDOWN || |
1696 |
< |
!submissionQueue.isEmpty() || |
1697 |
< |
(runState & ACTIVE_COUNT_MASK) != 0) |
1698 |
< |
return false; |
1699 |
< |
|
1700 |
< |
if (advanceRunLevel(TERMINATING)) |
1701 |
< |
startTerminating(); |
1702 |
< |
|
1703 |
< |
// Finish now if all threads terminated; else in some subsequent call |
1147 |
< |
if ((workerCounts >>> TOTAL_COUNT_SHIFT) == 0) { |
1148 |
< |
advanceRunLevel(TERMINATED); |
1149 |
< |
termination.forceTermination(); |
1150 |
< |
} |
1151 |
< |
return true; |
1692 |
> |
final void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) { |
1693 |
> |
WorkQueue[] ws; |
1694 |
> |
int m = runState & SMASK; |
1695 |
> |
if ((ws = workQueues) != null && ws.length > m) { |
1696 |
> |
for (int j = 1; j <= m && task.status >= 0; j += 2) { |
1697 |
> |
WorkQueue q = ws[j]; |
1698 |
> |
if (q != null && q.pollFor(task)) { |
1699 |
> |
joiner.runSubtask(task); |
1700 |
> |
break; |
1701 |
> |
} |
1702 |
> |
} |
1703 |
> |
} |
1704 |
|
} |
1705 |
|
|
1706 |
|
/** |
1707 |
< |
* Actions on transition to TERMINATING |
1708 |
< |
* |
1709 |
< |
* Runs up to four passes through workers: (0) shutting down each |
1710 |
< |
* (without waking up if parked) to quickly spread notifications |
1711 |
< |
* without unnecessary bouncing around event queues etc (1) wake |
1712 |
< |
* up and help cancel tasks (2) interrupt (3) mop up races with |
1713 |
< |
* interrupted workers |
1714 |
< |
*/ |
1715 |
< |
private void startTerminating() { |
1716 |
< |
cancelSubmissions(); |
1717 |
< |
for (int passes = 0; passes < 4 && workerCounts != 0; ++passes) { |
1718 |
< |
int c; // advance event count |
1719 |
< |
UNSAFE.compareAndSwapInt(this, eventCountOffset, |
1720 |
< |
c = eventCount, c+1); |
1721 |
< |
eventWaiters = 0L; // clobber lists |
1170 |
< |
spareWaiters = 0; |
1171 |
< |
for (ForkJoinWorkerThread w : workers) { |
1172 |
< |
if (w != null) { |
1173 |
< |
w.shutdown(); |
1174 |
< |
if (passes > 0 && !w.isTerminated()) { |
1175 |
< |
w.cancelTasks(); |
1176 |
< |
LockSupport.unpark(w); |
1177 |
< |
if (passes > 1 && !w.isInterrupted()) { |
1178 |
< |
try { |
1179 |
< |
w.interrupt(); |
1180 |
< |
} catch (SecurityException ignore) { |
1181 |
< |
} |
1182 |
< |
} |
1707 |
> |
* Returns a non-empty steal queue, if one is found during a random, |
1708 |
> |
* then cyclic scan, else null. This method must be retried by |
1709 |
> |
* caller if, by the time it tries to use the queue, it is empty. |
1710 |
> |
*/ |
1711 |
> |
private WorkQueue findNonEmptyStealQueue(WorkQueue w) { |
1712 |
> |
int r = w.seed; // Same idea as scan(), but ignoring submissions |
1713 |
> |
for (WorkQueue[] ws;;) { |
1714 |
> |
int m = runState & SMASK; |
1715 |
> |
if ((ws = workQueues) == null) |
1716 |
> |
return null; |
1717 |
> |
if (ws.length > m) { |
1718 |
> |
WorkQueue q; |
1719 |
> |
for (int k = 0, j = -1 - m;; ++j) { |
1720 |
> |
if (j < 0) { |
1721 |
> |
r ^= r << 13; r ^= r >>> 17; k = r ^= r << 5; |
1722 |
|
} |
1723 |
+ |
else |
1724 |
+ |
k += 7; |
1725 |
+ |
if ((q = ws[(k | 1) & m]) != null && q.base - q.top < 0) { |
1726 |
+ |
w.seed = r; |
1727 |
+ |
return q; |
1728 |
+ |
} |
1729 |
+ |
else if (j - m > m) |
1730 |
+ |
return null; |
1731 |
|
} |
1732 |
|
} |
1733 |
|
} |
1734 |
|
} |
1735 |
|
|
1736 |
|
/** |
1737 |
< |
* Clears out and cancels submissions, ignoring exceptions. |
1738 |
< |
*/ |
1739 |
< |
private void cancelSubmissions() { |
1740 |
< |
ForkJoinTask<?> task; |
1741 |
< |
while ((task = submissionQueue.poll()) != null) { |
1742 |
< |
try { |
1743 |
< |
task.cancel(false); |
1744 |
< |
} catch (Throwable ignore) { |
1737 |
> |
* Runs tasks until {@code isQuiescent()}. We piggyback on |
1738 |
> |
* active count ctl maintenance, but rather than blocking |
1739 |
> |
* when tasks cannot be found, we rescan until all others cannot |
1740 |
> |
* find tasks either. |
1741 |
> |
*/ |
1742 |
> |
final void helpQuiescePool(WorkQueue w) { |
1743 |
> |
for (boolean active = true;;) { |
1744 |
> |
w.runLocalTasks(); // exhaust local queue |
1745 |
> |
WorkQueue q = findNonEmptyStealQueue(w); |
1746 |
> |
if (q != null) { |
1747 |
> |
ForkJoinTask<?> t; |
1748 |
> |
if (!active) { // re-establish active count |
1749 |
> |
long c; |
1750 |
> |
active = true; |
1751 |
> |
do {} while (!U.compareAndSwapLong |
1752 |
> |
(this, CTL, c = ctl, c + AC_UNIT)); |
1753 |
> |
} |
1754 |
> |
if ((t = q.poll()) != null) |
1755 |
> |
w.runSubtask(t); |
1756 |
> |
} |
1757 |
> |
else { |
1758 |
> |
long c; |
1759 |
> |
if (active) { // decrement active count without queuing |
1760 |
> |
active = false; |
1761 |
> |
do {} while (!U.compareAndSwapLong |
1762 |
> |
(this, CTL, c = ctl, c -= AC_UNIT)); |
1763 |
> |
} |
1764 |
> |
else |
1765 |
> |
c = ctl; // re-increment on exit |
1766 |
> |
if ((int)(c >> AC_SHIFT) + parallelism == 0) { |
1767 |
> |
do {} while (!U.compareAndSwapLong |
1768 |
> |
(this, CTL, c = ctl, c + AC_UNIT)); |
1769 |
> |
break; |
1770 |
> |
} |
1771 |
|
} |
1772 |
|
} |
1773 |
|
} |
1774 |
|
|
1202 |
– |
// misc support for ForkJoinWorkerThread |
1203 |
– |
|
1204 |
– |
/** |
1205 |
– |
* Returns pool number. |
1206 |
– |
*/ |
1207 |
– |
final int getPoolNumber() { |
1208 |
– |
return poolNumber; |
1209 |
– |
} |
1210 |
– |
|
1775 |
|
/** |
1776 |
< |
* Tries to accumulate steal count from a worker, clearing |
1213 |
< |
* the worker's value if successful. |
1776 |
> |
* Gets and removes a local or stolen task for the given worker. |
1777 |
|
* |
1778 |
< |
* @return true if worker steal count now zero |
1778 |
> |
* @return a task, if available |
1779 |
|
*/ |
1780 |
< |
final boolean tryAccumulateStealCount(ForkJoinWorkerThread w) { |
1781 |
< |
int sc = w.stealCount; |
1782 |
< |
long c = stealCount; |
1783 |
< |
// CAS even if zero, for fence effects |
1784 |
< |
if (UNSAFE.compareAndSwapLong(this, stealCountOffset, c, c + sc)) { |
1785 |
< |
if (sc != 0) |
1786 |
< |
w.stealCount = 0; |
1787 |
< |
return true; |
1780 |
> |
final ForkJoinTask<?> nextTaskFor(WorkQueue w) { |
1781 |
> |
for (ForkJoinTask<?> t;;) { |
1782 |
> |
WorkQueue q; |
1783 |
> |
if ((t = w.nextLocalTask()) != null) |
1784 |
> |
return t; |
1785 |
> |
if ((q = findNonEmptyStealQueue(w)) == null) |
1786 |
> |
return null; |
1787 |
> |
if ((t = q.poll()) != null) |
1788 |
> |
return t; |
1789 |
|
} |
1226 |
– |
return sc == 0; |
1790 |
|
} |
1791 |
|
|
1792 |
|
/** |
1793 |
|
* Returns the approximate (non-atomic) number of idle threads per |
1794 |
< |
* active thread. |
1794 |
> |
* active thread to offset steal queue size for method |
1795 |
> |
* ForkJoinTask.getSurplusQueuedTaskCount(). |
1796 |
|
*/ |
1797 |
|
final int idlePerActive() { |
1798 |
< |
int pc = parallelism; // use parallelism, not rc |
1799 |
< |
int ac = runState; // no mask -- artificially boosts during shutdown |
1800 |
< |
// Use exact results for small values, saturate past 4 |
1801 |
< |
return ((pc <= ac) ? 0 : |
1802 |
< |
(pc >>> 1 <= ac) ? 1 : |
1803 |
< |
(pc >>> 2 <= ac) ? 3 : |
1804 |
< |
pc >>> 3); |
1798 |
> |
// Approximate at powers of two for small values, saturate past 4 |
1799 |
> |
int p = parallelism; |
1800 |
> |
int a = p + (int)(ctl >> AC_SHIFT); |
1801 |
> |
return (a > (p >>>= 1) ? 0 : |
1802 |
> |
a > (p >>>= 1) ? 1 : |
1803 |
> |
a > (p >>>= 1) ? 2 : |
1804 |
> |
a > (p >>>= 1) ? 4 : |
1805 |
> |
8); |
1806 |
> |
} |
1807 |
> |
|
1808 |
> |
// Termination |
1809 |
> |
|
1810 |
> |
/** |
1811 |
> |
* Possibly initiates and/or completes termination. The caller |
1812 |
> |
* triggering termination runs three passes through workQueues: |
1813 |
> |
* (0) Setting termination status, followed by wakeups of queued |
1814 |
> |
* workers; (1) cancelling all tasks; (2) interrupting lagging |
1815 |
> |
* threads (likely in external tasks, but possibly also blocked in |
1816 |
> |
* joins). Each pass repeats previous steps because of potential |
1817 |
> |
* lagging thread creation. |
1818 |
> |
* |
1819 |
> |
* @param now if true, unconditionally terminate, else only |
1820 |
> |
* if no work and no active workers |
1821 |
> |
* @paran enable if true, enable shutdown when next possible |
1822 |
> |
* @return true if now terminating or terminated |
1823 |
> |
*/ |
1824 |
> |
private boolean tryTerminate(boolean now, boolean enable) { |
1825 |
> |
Mutex lock = this.lock; |
1826 |
> |
for (long c;;) { |
1827 |
> |
if (((c = ctl) & STOP_BIT) != 0) { // already terminating |
1828 |
> |
if ((short)(c >>> TC_SHIFT) == -parallelism) { |
1829 |
> |
lock.lock(); // don't need try/finally |
1830 |
> |
termination.signalAll(); // signal when 0 workers |
1831 |
> |
lock.unlock(); |
1832 |
> |
} |
1833 |
> |
return true; |
1834 |
> |
} |
1835 |
> |
if (runState >= 0) { // not yet enabled |
1836 |
> |
if (!enable) |
1837 |
> |
return false; |
1838 |
> |
lock.lock(); |
1839 |
> |
runState |= SHUTDOWN; |
1840 |
> |
lock.unlock(); |
1841 |
> |
} |
1842 |
> |
if (!now) { // check if idle & no tasks |
1843 |
> |
if ((int)(c >> AC_SHIFT) != -parallelism || |
1844 |
> |
hasQueuedSubmissions()) |
1845 |
> |
return false; |
1846 |
> |
// Check for unqueued inactive workers. One pass suffices. |
1847 |
> |
WorkQueue[] ws = workQueues; WorkQueue w; |
1848 |
> |
if (ws != null) { |
1849 |
> |
for (int i = 1; i < ws.length; i += 2) { |
1850 |
> |
if ((w = ws[i]) != null && w.eventCount >= 0) |
1851 |
> |
return false; |
1852 |
> |
} |
1853 |
> |
} |
1854 |
> |
} |
1855 |
> |
if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) { |
1856 |
> |
for (int pass = 0; pass < 3; ++pass) { |
1857 |
> |
WorkQueue[] ws = workQueues; |
1858 |
> |
if (ws != null) { |
1859 |
> |
WorkQueue w; |
1860 |
> |
int n = ws.length; |
1861 |
> |
for (int i = 0; i < n; ++i) { |
1862 |
> |
if ((w = ws[i]) != null) { |
1863 |
> |
w.runState = -1; |
1864 |
> |
if (pass > 0) { |
1865 |
> |
w.cancelAll(); |
1866 |
> |
if (pass > 1) |
1867 |
> |
w.interruptOwner(); |
1868 |
> |
} |
1869 |
> |
} |
1870 |
> |
} |
1871 |
> |
// Wake up workers parked on event queue |
1872 |
> |
int i, e; long cc; Thread p; |
1873 |
> |
while ((e = (int)(cc = ctl) & E_MASK) != 0 && |
1874 |
> |
(i = e & SMASK) < n && |
1875 |
> |
(w = ws[i]) != null) { |
1876 |
> |
long nc = ((long)(w.nextWait & E_MASK) | |
1877 |
> |
((cc + AC_UNIT) & AC_MASK) | |
1878 |
> |
(cc & (TC_MASK|STOP_BIT))); |
1879 |
> |
if (w.eventCount == (e | INT_SIGN) && |
1880 |
> |
U.compareAndSwapLong(this, CTL, cc, nc)) { |
1881 |
> |
w.eventCount = (e + E_SEQ) & E_MASK; |
1882 |
> |
w.runState = -1; |
1883 |
> |
if ((p = w.parker) != null) |
1884 |
> |
U.unpark(p); |
1885 |
> |
} |
1886 |
> |
} |
1887 |
> |
} |
1888 |
> |
} |
1889 |
> |
} |
1890 |
> |
} |
1891 |
|
} |
1892 |
|
|
1893 |
< |
// Public and protected methods |
1893 |
> |
// Exported methods |
1894 |
|
|
1895 |
|
// Constructors |
1896 |
|
|
1959 |
|
checkPermission(); |
1960 |
|
if (factory == null) |
1961 |
|
throw new NullPointerException(); |
1962 |
< |
if (parallelism <= 0 || parallelism > MAX_WORKERS) |
1962 |
> |
if (parallelism <= 0 || parallelism > POOL_MAX) |
1963 |
|
throw new IllegalArgumentException(); |
1964 |
|
this.parallelism = parallelism; |
1965 |
|
this.factory = factory; |
1966 |
|
this.ueh = handler; |
1967 |
< |
this.locallyFifo = asyncMode; |
1968 |
< |
int arraySize = initialArraySizeFor(parallelism); |
1969 |
< |
this.workers = new ForkJoinWorkerThread[arraySize]; |
1970 |
< |
this.submissionQueue = new LinkedTransferQueue<ForkJoinTask<?>>(); |
1971 |
< |
this.workerLock = new ReentrantLock(); |
1972 |
< |
this.termination = new Phaser(1); |
1973 |
< |
this.poolNumber = poolNumberGenerator.incrementAndGet(); |
1974 |
< |
} |
1975 |
< |
|
1976 |
< |
/** |
1977 |
< |
* Returns initial power of two size for workers array. |
1978 |
< |
* @param pc the initial parallelism level |
1979 |
< |
*/ |
1980 |
< |
private static int initialArraySizeFor(int pc) { |
1981 |
< |
// If possible, initially allocate enough space for one spare |
1982 |
< |
int size = pc < MAX_WORKERS ? pc + 1 : MAX_WORKERS; |
1983 |
< |
// See Hackers Delight, sec 3.2. We know MAX_WORKERS < (1 >>> 16) |
1984 |
< |
size |= size >>> 1; |
1985 |
< |
size |= size >>> 2; |
1336 |
< |
size |= size >>> 4; |
1337 |
< |
size |= size >>> 8; |
1338 |
< |
return size + 1; |
1967 |
> |
this.localMode = asyncMode ? FIFO_QUEUE : LIFO_QUEUE; |
1968 |
> |
this.growHints = 1; |
1969 |
> |
long np = (long)(-parallelism); // offset ctl counts |
1970 |
> |
this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK); |
1971 |
> |
// initialize workQueues array with room for 2*parallelism if possible |
1972 |
> |
int n = parallelism << 1; |
1973 |
> |
if (n >= POOL_MAX) |
1974 |
> |
n = POOL_MAX; |
1975 |
> |
else { // See Hackers Delight, sec 3.2, where n < (1 << 16) |
1976 |
> |
n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; |
1977 |
> |
} |
1978 |
> |
this.workQueues = new WorkQueue[(n + 1) << 1]; // #slots = 2 * #workers |
1979 |
> |
this.termination = (this.lock = new Mutex()).newCondition(); |
1980 |
> |
this.stealCount = new AtomicLong(); |
1981 |
> |
this.nextWorkerNumber = new AtomicInteger(); |
1982 |
> |
StringBuilder sb = new StringBuilder("ForkJoinPool-"); |
1983 |
> |
sb.append(poolNumberGenerator.incrementAndGet()); |
1984 |
> |
sb.append("-worker-"); |
1985 |
> |
this.workerNamePrefix = sb.toString(); |
1986 |
|
} |
1987 |
|
|
1988 |
|
// Execution methods |
1989 |
|
|
1990 |
|
/** |
1344 |
– |
* Submits task and creates, starts, or resumes some workers if necessary |
1345 |
– |
*/ |
1346 |
– |
private <T> void doSubmit(ForkJoinTask<T> task) { |
1347 |
– |
submissionQueue.offer(task); |
1348 |
– |
int c; // try to increment event count -- CAS failure OK |
1349 |
– |
UNSAFE.compareAndSwapInt(this, eventCountOffset, c = eventCount, c+1); |
1350 |
– |
helpMaintainParallelism(); |
1351 |
– |
} |
1352 |
– |
|
1353 |
– |
/** |
1991 |
|
* Performs the given task, returning its result upon completion. |
1992 |
+ |
* If the computation encounters an unchecked Exception or Error, |
1993 |
+ |
* it is rethrown as the outcome of this invocation. Rethrown |
1994 |
+ |
* exceptions behave in the same way as regular exceptions, but, |
1995 |
+ |
* when possible, contain stack traces (as displayed for example |
1996 |
+ |
* using {@code ex.printStackTrace()}) of both the current thread |
1997 |
+ |
* as well as the thread actually encountering the exception; |
1998 |
+ |
* minimally only the latter. |
1999 |
|
* |
2000 |
|
* @param task the task |
2001 |
|
* @return the task's result |
2004 |
|
* scheduled for execution |
2005 |
|
*/ |
2006 |
|
public <T> T invoke(ForkJoinTask<T> task) { |
2007 |
< |
if (task == null) |
2008 |
< |
throw new NullPointerException(); |
1365 |
< |
if (runState >= SHUTDOWN) |
1366 |
< |
throw new RejectedExecutionException(); |
1367 |
< |
Thread t = Thread.currentThread(); |
1368 |
< |
if ((t instanceof ForkJoinWorkerThread) && |
1369 |
< |
((ForkJoinWorkerThread)t).pool == this) |
1370 |
< |
return task.invoke(); // bypass submit if in same pool |
1371 |
< |
else { |
1372 |
< |
doSubmit(task); |
1373 |
< |
return task.join(); |
1374 |
< |
} |
1375 |
< |
} |
1376 |
< |
|
1377 |
< |
/** |
1378 |
< |
* Unless terminating, forks task if within an ongoing FJ |
1379 |
< |
* computation in the current pool, else submits as external task. |
1380 |
< |
*/ |
1381 |
< |
private <T> void forkOrSubmit(ForkJoinTask<T> task) { |
1382 |
< |
if (runState >= SHUTDOWN) |
1383 |
< |
throw new RejectedExecutionException(); |
1384 |
< |
Thread t = Thread.currentThread(); |
1385 |
< |
if ((t instanceof ForkJoinWorkerThread) && |
1386 |
< |
((ForkJoinWorkerThread)t).pool == this) |
1387 |
< |
task.fork(); |
1388 |
< |
else |
1389 |
< |
doSubmit(task); |
2007 |
> |
doSubmit(task); |
2008 |
> |
return task.join(); |
2009 |
|
} |
2010 |
|
|
2011 |
|
/** |
2017 |
|
* scheduled for execution |
2018 |
|
*/ |
2019 |
|
public void execute(ForkJoinTask<?> task) { |
2020 |
< |
if (task == null) |
1402 |
< |
throw new NullPointerException(); |
1403 |
< |
forkOrSubmit(task); |
2020 |
> |
doSubmit(task); |
2021 |
|
} |
2022 |
|
|
2023 |
|
// AbstractExecutorService methods |
2035 |
|
job = (ForkJoinTask<?>) task; |
2036 |
|
else |
2037 |
|
job = ForkJoinTask.adapt(task, null); |
2038 |
< |
forkOrSubmit(job); |
2038 |
> |
doSubmit(job); |
2039 |
|
} |
2040 |
|
|
2041 |
|
/** |
2048 |
|
* scheduled for execution |
2049 |
|
*/ |
2050 |
|
public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) { |
2051 |
< |
if (task == null) |
1435 |
< |
throw new NullPointerException(); |
1436 |
< |
forkOrSubmit(task); |
2051 |
> |
doSubmit(task); |
2052 |
|
return task; |
2053 |
|
} |
2054 |
|
|
2061 |
|
if (task == null) |
2062 |
|
throw new NullPointerException(); |
2063 |
|
ForkJoinTask<T> job = ForkJoinTask.adapt(task); |
2064 |
< |
forkOrSubmit(job); |
2064 |
> |
doSubmit(job); |
2065 |
|
return job; |
2066 |
|
} |
2067 |
|
|
2074 |
|
if (task == null) |
2075 |
|
throw new NullPointerException(); |
2076 |
|
ForkJoinTask<T> job = ForkJoinTask.adapt(task, result); |
2077 |
< |
forkOrSubmit(job); |
2077 |
> |
doSubmit(job); |
2078 |
|
return job; |
2079 |
|
} |
2080 |
|
|
2091 |
|
job = (ForkJoinTask<?>) task; |
2092 |
|
else |
2093 |
|
job = ForkJoinTask.adapt(task, null); |
2094 |
< |
forkOrSubmit(job); |
2094 |
> |
doSubmit(job); |
2095 |
|
return job; |
2096 |
|
} |
2097 |
|
|
2100 |
|
* @throws RejectedExecutionException {@inheritDoc} |
2101 |
|
*/ |
2102 |
|
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) { |
2103 |
< |
ArrayList<ForkJoinTask<T>> forkJoinTasks = |
2104 |
< |
new ArrayList<ForkJoinTask<T>>(tasks.size()); |
2105 |
< |
for (Callable<T> task : tasks) |
2106 |
< |
forkJoinTasks.add(ForkJoinTask.adapt(task)); |
2107 |
< |
invoke(new InvokeAll<T>(forkJoinTasks)); |
2108 |
< |
|
2103 |
> |
// In previous versions of this class, this method constructed |
2104 |
> |
// a task to run ForkJoinTask.invokeAll, but now external |
2105 |
> |
// invocation of multiple tasks is at least as efficient. |
2106 |
> |
List<ForkJoinTask<T>> fs = new ArrayList<ForkJoinTask<T>>(tasks.size()); |
2107 |
> |
// Workaround needed because method wasn't declared with |
2108 |
> |
// wildcards in return type but should have been. |
2109 |
|
@SuppressWarnings({"unchecked", "rawtypes"}) |
2110 |
< |
List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks; |
1496 |
< |
return futures; |
1497 |
< |
} |
2110 |
> |
List<Future<T>> futures = (List<Future<T>>) (List) fs; |
2111 |
|
|
2112 |
< |
static final class InvokeAll<T> extends RecursiveAction { |
2113 |
< |
final ArrayList<ForkJoinTask<T>> tasks; |
2114 |
< |
InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; } |
2115 |
< |
public void compute() { |
2116 |
< |
try { invokeAll(tasks); } |
2117 |
< |
catch (Exception ignore) {} |
2112 |
> |
boolean done = false; |
2113 |
> |
try { |
2114 |
> |
for (Callable<T> t : tasks) { |
2115 |
> |
ForkJoinTask<T> f = ForkJoinTask.adapt(t); |
2116 |
> |
doSubmit(f); |
2117 |
> |
fs.add(f); |
2118 |
> |
} |
2119 |
> |
for (ForkJoinTask<T> f : fs) |
2120 |
> |
f.quietlyJoin(); |
2121 |
> |
done = true; |
2122 |
> |
return futures; |
2123 |
> |
} finally { |
2124 |
> |
if (!done) |
2125 |
> |
for (ForkJoinTask<T> f : fs) |
2126 |
> |
f.cancel(false); |
2127 |
|
} |
1506 |
– |
private static final long serialVersionUID = -7914297376763021607L; |
2128 |
|
} |
2129 |
|
|
2130 |
|
/** |
2164 |
|
* @return the number of worker threads |
2165 |
|
*/ |
2166 |
|
public int getPoolSize() { |
2167 |
< |
return workerCounts >>> TOTAL_COUNT_SHIFT; |
2167 |
> |
return parallelism + (short)(ctl >>> TC_SHIFT); |
2168 |
|
} |
2169 |
|
|
2170 |
|
/** |
2174 |
|
* @return {@code true} if this pool uses async mode |
2175 |
|
*/ |
2176 |
|
public boolean getAsyncMode() { |
2177 |
< |
return locallyFifo; |
2177 |
> |
return localMode != 0; |
2178 |
|
} |
2179 |
|
|
2180 |
|
/** |
2186 |
|
* @return the number of worker threads |
2187 |
|
*/ |
2188 |
|
public int getRunningThreadCount() { |
2189 |
< |
return workerCounts & RUNNING_COUNT_MASK; |
2189 |
> |
int rc = 0; |
2190 |
> |
WorkQueue[] ws; WorkQueue w; |
2191 |
> |
if ((ws = workQueues) != null) { |
2192 |
> |
for (int i = 1; i < ws.length; i += 2) { |
2193 |
> |
if ((w = ws[i]) != null && w.isApparentlyUnblocked()) |
2194 |
> |
++rc; |
2195 |
> |
} |
2196 |
> |
} |
2197 |
> |
return rc; |
2198 |
|
} |
2199 |
|
|
2200 |
|
/** |
2205 |
|
* @return the number of active threads |
2206 |
|
*/ |
2207 |
|
public int getActiveThreadCount() { |
2208 |
< |
return runState & ACTIVE_COUNT_MASK; |
2208 |
> |
int r = parallelism + (int)(ctl >> AC_SHIFT); |
2209 |
> |
return (r <= 0) ? 0 : r; // suppress momentarily negative values |
2210 |
|
} |
2211 |
|
|
2212 |
|
/** |
2221 |
|
* @return {@code true} if all threads are currently idle |
2222 |
|
*/ |
2223 |
|
public boolean isQuiescent() { |
2224 |
< |
return (runState & ACTIVE_COUNT_MASK) == 0; |
2224 |
> |
return (int)(ctl >> AC_SHIFT) + parallelism == 0; |
2225 |
|
} |
2226 |
|
|
2227 |
|
/** |
2236 |
|
* @return the number of steals |
2237 |
|
*/ |
2238 |
|
public long getStealCount() { |
2239 |
< |
return stealCount; |
2239 |
> |
long count = stealCount.get(); |
2240 |
> |
WorkQueue[] ws; WorkQueue w; |
2241 |
> |
if ((ws = workQueues) != null) { |
2242 |
> |
for (int i = 1; i < ws.length; i += 2) { |
2243 |
> |
if ((w = ws[i]) != null) |
2244 |
> |
count += w.totalSteals; |
2245 |
> |
} |
2246 |
> |
} |
2247 |
> |
return count; |
2248 |
|
} |
2249 |
|
|
2250 |
|
/** |
2259 |
|
*/ |
2260 |
|
public long getQueuedTaskCount() { |
2261 |
|
long count = 0; |
2262 |
< |
for (ForkJoinWorkerThread w : workers) |
2263 |
< |
if (w != null) |
2264 |
< |
count += w.getQueueSize(); |
2262 |
> |
WorkQueue[] ws; WorkQueue w; |
2263 |
> |
if ((ws = workQueues) != null) { |
2264 |
> |
for (int i = 1; i < ws.length; i += 2) { |
2265 |
> |
if ((w = ws[i]) != null) |
2266 |
> |
count += w.queueSize(); |
2267 |
> |
} |
2268 |
> |
} |
2269 |
|
return count; |
2270 |
|
} |
2271 |
|
|
2272 |
|
/** |
2273 |
|
* Returns an estimate of the number of tasks submitted to this |
2274 |
< |
* pool that have not yet begun executing. This method takes time |
2275 |
< |
* proportional to the number of submissions. |
2274 |
> |
* pool that have not yet begun executing. This method may take |
2275 |
> |
* time proportional to the number of submissions. |
2276 |
|
* |
2277 |
|
* @return the number of queued submissions |
2278 |
|
*/ |
2279 |
|
public int getQueuedSubmissionCount() { |
2280 |
< |
return submissionQueue.size(); |
2280 |
> |
int count = 0; |
2281 |
> |
WorkQueue[] ws; WorkQueue w; |
2282 |
> |
if ((ws = workQueues) != null) { |
2283 |
> |
for (int i = 0; i < ws.length; i += 2) { |
2284 |
> |
if ((w = ws[i]) != null) |
2285 |
> |
count += w.queueSize(); |
2286 |
> |
} |
2287 |
> |
} |
2288 |
> |
return count; |
2289 |
|
} |
2290 |
|
|
2291 |
|
/** |
2295 |
|
* @return {@code true} if there are any queued submissions |
2296 |
|
*/ |
2297 |
|
public boolean hasQueuedSubmissions() { |
2298 |
< |
return !submissionQueue.isEmpty(); |
2298 |
> |
WorkQueue[] ws; WorkQueue w; |
2299 |
> |
if ((ws = workQueues) != null) { |
2300 |
> |
for (int i = 0; i < ws.length; i += 2) { |
2301 |
> |
if ((w = ws[i]) != null && w.queueSize() != 0) |
2302 |
> |
return true; |
2303 |
> |
} |
2304 |
> |
} |
2305 |
> |
return false; |
2306 |
|
} |
2307 |
|
|
2308 |
|
/** |
2313 |
|
* @return the next submission, or {@code null} if none |
2314 |
|
*/ |
2315 |
|
protected ForkJoinTask<?> pollSubmission() { |
2316 |
< |
return submissionQueue.poll(); |
2316 |
> |
WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t; |
2317 |
> |
if ((ws = workQueues) != null) { |
2318 |
> |
for (int i = 0; i < ws.length; i += 2) { |
2319 |
> |
if ((w = ws[i]) != null && (t = w.poll()) != null) |
2320 |
> |
return t; |
2321 |
> |
} |
2322 |
> |
} |
2323 |
> |
return null; |
2324 |
|
} |
2325 |
|
|
2326 |
|
/** |
2341 |
|
* @return the number of elements transferred |
2342 |
|
*/ |
2343 |
|
protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) { |
2344 |
< |
int count = submissionQueue.drainTo(c); |
2345 |
< |
for (ForkJoinWorkerThread w : workers) |
2346 |
< |
if (w != null) |
2347 |
< |
count += w.drainTasksTo(c); |
2344 |
> |
int count = 0; |
2345 |
> |
WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t; |
2346 |
> |
if ((ws = workQueues) != null) { |
2347 |
> |
for (int i = 0; i < ws.length; ++i) { |
2348 |
> |
if ((w = ws[i]) != null) { |
2349 |
> |
while ((t = w.poll()) != null) { |
2350 |
> |
c.add(t); |
2351 |
> |
++count; |
2352 |
> |
} |
2353 |
> |
} |
2354 |
> |
} |
2355 |
> |
} |
2356 |
|
return count; |
2357 |
|
} |
2358 |
|
|
2364 |
|
* @return a string identifying this pool, as well as its state |
2365 |
|
*/ |
2366 |
|
public String toString() { |
2367 |
< |
long st = getStealCount(); |
2368 |
< |
long qt = getQueuedTaskCount(); |
2369 |
< |
long qs = getQueuedSubmissionCount(); |
2370 |
< |
int wc = workerCounts; |
2371 |
< |
int tc = wc >>> TOTAL_COUNT_SHIFT; |
2372 |
< |
int rc = wc & RUNNING_COUNT_MASK; |
2367 |
> |
// Use a single pass through workQueues to collect counts |
2368 |
> |
long qt = 0L, qs = 0L; int rc = 0; |
2369 |
> |
long st = stealCount.get(); |
2370 |
> |
long c = ctl; |
2371 |
> |
WorkQueue[] ws; WorkQueue w; |
2372 |
> |
if ((ws = workQueues) != null) { |
2373 |
> |
for (int i = 0; i < ws.length; ++i) { |
2374 |
> |
if ((w = ws[i]) != null) { |
2375 |
> |
int size = w.queueSize(); |
2376 |
> |
if ((i & 1) == 0) |
2377 |
> |
qs += size; |
2378 |
> |
else { |
2379 |
> |
qt += size; |
2380 |
> |
st += w.totalSteals; |
2381 |
> |
if (w.isApparentlyUnblocked()) |
2382 |
> |
++rc; |
2383 |
> |
} |
2384 |
> |
} |
2385 |
> |
} |
2386 |
> |
} |
2387 |
|
int pc = parallelism; |
2388 |
< |
int rs = runState; |
2389 |
< |
int ac = rs & ACTIVE_COUNT_MASK; |
2388 |
> |
int tc = pc + (short)(c >>> TC_SHIFT); |
2389 |
> |
int ac = pc + (int)(c >> AC_SHIFT); |
2390 |
> |
if (ac < 0) // ignore transient negative |
2391 |
> |
ac = 0; |
2392 |
> |
String level; |
2393 |
> |
if ((c & STOP_BIT) != 0) |
2394 |
> |
level = (tc == 0) ? "Terminated" : "Terminating"; |
2395 |
> |
else |
2396 |
> |
level = runState < 0 ? "Shutting down" : "Running"; |
2397 |
|
return super.toString() + |
2398 |
< |
"[" + runLevelToString(rs) + |
2398 |
> |
"[" + level + |
2399 |
|
", parallelism = " + pc + |
2400 |
|
", size = " + tc + |
2401 |
|
", active = " + ac + |
2406 |
|
"]"; |
2407 |
|
} |
2408 |
|
|
1716 |
– |
private static String runLevelToString(int s) { |
1717 |
– |
return ((s & TERMINATED) != 0 ? "Terminated" : |
1718 |
– |
((s & TERMINATING) != 0 ? "Terminating" : |
1719 |
– |
((s & SHUTDOWN) != 0 ? "Shutting down" : |
1720 |
– |
"Running"))); |
1721 |
– |
} |
1722 |
– |
|
2409 |
|
/** |
2410 |
|
* Initiates an orderly shutdown in which previously submitted |
2411 |
|
* tasks are executed, but no new tasks will be accepted. |
2420 |
|
*/ |
2421 |
|
public void shutdown() { |
2422 |
|
checkPermission(); |
2423 |
< |
advanceRunLevel(SHUTDOWN); |
1738 |
< |
tryTerminate(false); |
2423 |
> |
tryTerminate(false, true); |
2424 |
|
} |
2425 |
|
|
2426 |
|
/** |
2441 |
|
*/ |
2442 |
|
public List<Runnable> shutdownNow() { |
2443 |
|
checkPermission(); |
2444 |
< |
tryTerminate(true); |
2444 |
> |
tryTerminate(true, true); |
2445 |
|
return Collections.emptyList(); |
2446 |
|
} |
2447 |
|
|
2451 |
|
* @return {@code true} if all tasks have completed following shut down |
2452 |
|
*/ |
2453 |
|
public boolean isTerminated() { |
2454 |
< |
return runState >= TERMINATED; |
2454 |
> |
long c = ctl; |
2455 |
> |
return ((c & STOP_BIT) != 0L && |
2456 |
> |
(short)(c >>> TC_SHIFT) == -parallelism); |
2457 |
|
} |
2458 |
|
|
2459 |
|
/** |
2461 |
|
* commenced but not yet completed. This method may be useful for |
2462 |
|
* debugging. A return of {@code true} reported a sufficient |
2463 |
|
* period after shutdown may indicate that submitted tasks have |
2464 |
< |
* ignored or suppressed interruption, causing this executor not |
2465 |
< |
* to properly terminate. |
2464 |
> |
* ignored or suppressed interruption, or are waiting for IO, |
2465 |
> |
* causing this executor not to properly terminate. (See the |
2466 |
> |
* advisory notes for class {@link ForkJoinTask} stating that |
2467 |
> |
* tasks should not normally entail blocking operations. But if |
2468 |
> |
* they do, they must abort them on interrupt.) |
2469 |
|
* |
2470 |
|
* @return {@code true} if terminating but not yet terminated |
2471 |
|
*/ |
2472 |
|
public boolean isTerminating() { |
2473 |
< |
return (runState & (TERMINATING|TERMINATED)) == TERMINATING; |
2474 |
< |
} |
2475 |
< |
|
1786 |
< |
/** |
1787 |
< |
* Returns true if terminating or terminated. Used by ForkJoinWorkerThread. |
1788 |
< |
*/ |
1789 |
< |
final boolean isAtLeastTerminating() { |
1790 |
< |
return runState >= TERMINATING; |
2473 |
> |
long c = ctl; |
2474 |
> |
return ((c & STOP_BIT) != 0L && |
2475 |
> |
(short)(c >>> TC_SHIFT) != -parallelism); |
2476 |
|
} |
2477 |
|
|
2478 |
|
/** |
2481 |
|
* @return {@code true} if this pool has been shut down |
2482 |
|
*/ |
2483 |
|
public boolean isShutdown() { |
2484 |
< |
return runState >= SHUTDOWN; |
2484 |
> |
return runState < 0; |
2485 |
|
} |
2486 |
|
|
2487 |
|
/** |
2497 |
|
*/ |
2498 |
|
public boolean awaitTermination(long timeout, TimeUnit unit) |
2499 |
|
throws InterruptedException { |
2500 |
+ |
long nanos = unit.toNanos(timeout); |
2501 |
+ |
final Mutex lock = this.lock; |
2502 |
+ |
lock.lock(); |
2503 |
|
try { |
2504 |
< |
termination.awaitAdvanceInterruptibly(0, timeout, unit); |
2505 |
< |
} catch (TimeoutException ex) { |
2506 |
< |
return false; |
2504 |
> |
for (;;) { |
2505 |
> |
if (isTerminated()) |
2506 |
> |
return true; |
2507 |
> |
if (nanos <= 0) |
2508 |
> |
return false; |
2509 |
> |
nanos = termination.awaitNanos(nanos); |
2510 |
> |
} |
2511 |
> |
} finally { |
2512 |
> |
lock.unlock(); |
2513 |
|
} |
1820 |
– |
return true; |
2514 |
|
} |
2515 |
|
|
2516 |
|
/** |
2521 |
|
* {@code isReleasable} must return {@code true} if blocking is |
2522 |
|
* not necessary. Method {@code block} blocks the current thread |
2523 |
|
* if necessary (perhaps internally invoking {@code isReleasable} |
2524 |
< |
* before actually blocking). The unusual methods in this API |
2525 |
< |
* accommodate synchronizers that may, but don't usually, block |
2526 |
< |
* for long periods. Similarly, they allow more efficient internal |
2527 |
< |
* handling of cases in which additional workers may be, but |
2528 |
< |
* usually are not, needed to ensure sufficient parallelism. |
2529 |
< |
* Toward this end, implementations of method {@code isReleasable} |
2530 |
< |
* must be amenable to repeated invocation. |
2524 |
> |
* before actually blocking). These actions are performed by any |
2525 |
> |
* thread invoking {@link ForkJoinPool#managedBlock}. The |
2526 |
> |
* unusual methods in this API accommodate synchronizers that may, |
2527 |
> |
* but don't usually, block for long periods. Similarly, they |
2528 |
> |
* allow more efficient internal handling of cases in which |
2529 |
> |
* additional workers may be, but usually are not, needed to |
2530 |
> |
* ensure sufficient parallelism. Toward this end, |
2531 |
> |
* implementations of method {@code isReleasable} must be amenable |
2532 |
> |
* to repeated invocation. |
2533 |
|
* |
2534 |
|
* <p>For example, here is a ManagedBlocker based on a |
2535 |
|
* ReentrantLock: |
2609 |
|
public static void managedBlock(ManagedBlocker blocker) |
2610 |
|
throws InterruptedException { |
2611 |
|
Thread t = Thread.currentThread(); |
2612 |
< |
if (t instanceof ForkJoinWorkerThread) { |
2613 |
< |
ForkJoinWorkerThread w = (ForkJoinWorkerThread) t; |
2614 |
< |
w.pool.awaitBlocker(blocker); |
2615 |
< |
} |
2616 |
< |
else { |
2617 |
< |
do {} while (!blocker.isReleasable() && !blocker.block()); |
2612 |
> |
ForkJoinPool p = ((t instanceof ForkJoinWorkerThread) ? |
2613 |
> |
((ForkJoinWorkerThread)t).pool : null); |
2614 |
> |
while (!blocker.isReleasable()) { |
2615 |
> |
if (p == null || p.tryCompensate()) { |
2616 |
> |
try { |
2617 |
> |
do {} while (!blocker.isReleasable() && !blocker.block()); |
2618 |
> |
} finally { |
2619 |
> |
if (p != null) |
2620 |
> |
p.incrementActiveCount(); |
2621 |
> |
} |
2622 |
> |
break; |
2623 |
> |
} |
2624 |
|
} |
2625 |
|
} |
2626 |
|
|
2637 |
|
} |
2638 |
|
|
2639 |
|
// Unsafe mechanics |
2640 |
< |
|
2641 |
< |
private static final sun.misc.Unsafe UNSAFE = getUnsafe(); |
2642 |
< |
private static final long workerCountsOffset = |
2643 |
< |
objectFieldOffset("workerCounts", ForkJoinPool.class); |
2644 |
< |
private static final long runStateOffset = |
2645 |
< |
objectFieldOffset("runState", ForkJoinPool.class); |
2646 |
< |
private static final long eventCountOffset = |
2647 |
< |
objectFieldOffset("eventCount", ForkJoinPool.class); |
2648 |
< |
private static final long eventWaitersOffset = |
2649 |
< |
objectFieldOffset("eventWaiters", ForkJoinPool.class); |
1949 |
< |
private static final long stealCountOffset = |
1950 |
< |
objectFieldOffset("stealCount", ForkJoinPool.class); |
1951 |
< |
private static final long spareWaitersOffset = |
1952 |
< |
objectFieldOffset("spareWaiters", ForkJoinPool.class); |
1953 |
< |
|
1954 |
< |
private static long objectFieldOffset(String field, Class<?> klazz) { |
2640 |
> |
private static final sun.misc.Unsafe U; |
2641 |
> |
private static final long CTL; |
2642 |
> |
private static final long PARKBLOCKER; |
2643 |
> |
|
2644 |
> |
static { |
2645 |
> |
poolNumberGenerator = new AtomicInteger(); |
2646 |
> |
modifyThreadPermission = new RuntimePermission("modifyThread"); |
2647 |
> |
defaultForkJoinWorkerThreadFactory = |
2648 |
> |
new DefaultForkJoinWorkerThreadFactory(); |
2649 |
> |
submitters = new ThreadSubmitter(); |
2650 |
|
try { |
2651 |
< |
return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field)); |
2652 |
< |
} catch (NoSuchFieldException e) { |
2653 |
< |
// Convert Exception to corresponding Error |
2654 |
< |
NoSuchFieldError error = new NoSuchFieldError(field); |
2655 |
< |
error.initCause(e); |
2656 |
< |
throw error; |
2651 |
> |
U = getUnsafe(); |
2652 |
> |
Class<?> k = ForkJoinPool.class; |
2653 |
> |
CTL = U.objectFieldOffset |
2654 |
> |
(k.getDeclaredField("ctl")); |
2655 |
> |
Class<?> tk = Thread.class; |
2656 |
> |
PARKBLOCKER = U.objectFieldOffset |
2657 |
> |
(tk.getDeclaredField("parkBlocker")); |
2658 |
> |
} catch (Exception e) { |
2659 |
> |
throw new Error(e); |
2660 |
|
} |
2661 |
|
} |
2662 |
|
|
2687 |
|
} |
2688 |
|
} |
2689 |
|
} |
2690 |
+ |
|
2691 |
|
} |