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; |
8 |
– |
|
9 |
– |
import java.util.concurrent.*; |
10 |
– |
|
8 |
|
import java.util.ArrayList; |
9 |
|
import java.util.Arrays; |
10 |
|
import java.util.Collection; |
11 |
|
import java.util.Collections; |
12 |
|
import java.util.List; |
13 |
< |
import java.util.concurrent.locks.LockSupport; |
14 |
< |
import java.util.concurrent.locks.ReentrantLock; |
13 |
> |
import java.util.Random; |
14 |
> |
import java.util.concurrent.AbstractExecutorService; |
15 |
> |
import java.util.concurrent.Callable; |
16 |
> |
import java.util.concurrent.ExecutorService; |
17 |
> |
import java.util.concurrent.Future; |
18 |
> |
import java.util.concurrent.RejectedExecutionException; |
19 |
> |
import java.util.concurrent.RunnableFuture; |
20 |
> |
import java.util.concurrent.TimeUnit; |
21 |
|
import java.util.concurrent.atomic.AtomicInteger; |
22 |
< |
import java.util.concurrent.CountDownLatch; |
22 |
> |
import java.util.concurrent.atomic.AtomicLong; |
23 |
> |
import java.util.concurrent.locks.AbstractQueuedSynchronizer; |
24 |
> |
import java.util.concurrent.locks.Condition; |
25 |
|
|
26 |
|
/** |
27 |
|
* An {@link ExecutorService} for running {@link ForkJoinTask}s. |
28 |
|
* A {@code ForkJoinPool} provides the entry point for submissions |
29 |
< |
* from non-{@code ForkJoinTask}s, as well as management and |
29 |
> |
* from non-{@code ForkJoinTask} clients, as well as management and |
30 |
|
* monitoring operations. |
31 |
|
* |
32 |
|
* <p>A {@code ForkJoinPool} differs from other kinds of {@link |
33 |
|
* ExecutorService} mainly by virtue of employing |
34 |
|
* <em>work-stealing</em>: all threads in the pool attempt to find and |
35 |
< |
* execute subtasks created by other active tasks (eventually blocking |
36 |
< |
* waiting for work if none exist). This enables efficient processing |
37 |
< |
* when most tasks spawn other subtasks (as do most {@code |
38 |
< |
* ForkJoinTask}s). A {@code ForkJoinPool} may also be used for mixed |
39 |
< |
* execution of some plain {@code Runnable}- or {@code Callable}- |
40 |
< |
* based activities along with {@code ForkJoinTask}s. When setting |
41 |
< |
* {@linkplain #setAsyncMode async mode}, a {@code ForkJoinPool} may |
42 |
< |
* also be appropriate for use with fine-grained tasks of any form |
38 |
< |
* that are never joined. Otherwise, other {@code ExecutorService} |
39 |
< |
* implementations are typically more appropriate choices. |
35 |
> |
* execute tasks submitted to the pool and/or created by other active |
36 |
> |
* tasks (eventually blocking waiting for work if none exist). This |
37 |
> |
* enables efficient processing when most tasks spawn other subtasks |
38 |
> |
* (as do most {@code ForkJoinTask}s), as well as when many small |
39 |
> |
* tasks are submitted to the pool from external clients. Especially |
40 |
> |
* when setting <em>asyncMode</em> to true in constructors, {@code |
41 |
> |
* ForkJoinPool}s may also be appropriate for use with event-style |
42 |
> |
* tasks that are never joined. |
43 |
|
* |
44 |
|
* <p>A {@code ForkJoinPool} is constructed with a given target |
45 |
|
* parallelism level; by default, equal to the number of available |
46 |
< |
* processors. Unless configured otherwise via {@link |
47 |
< |
* #setMaintainsParallelism}, the pool attempts to maintain this |
48 |
< |
* number of active (or available) threads by dynamically adding, |
49 |
< |
* suspending, or resuming internal worker threads, even if some tasks |
50 |
< |
* are stalled waiting to join others. However, no such adjustments |
51 |
< |
* are performed in the face of blocked IO or other unmanaged |
52 |
< |
* synchronization. The nested {@link ManagedBlocker} interface |
50 |
< |
* enables extension of the kinds of synchronization accommodated. |
51 |
< |
* The target parallelism level may also be changed dynamically |
52 |
< |
* ({@link #setParallelism}). The total number of threads may be |
53 |
< |
* limited using method {@link #setMaximumPoolSize}, in which case it |
54 |
< |
* may become possible for the activities of a pool to stall due to |
55 |
< |
* the lack of available threads to process new tasks. When the pool |
56 |
< |
* is executing tasks, these and other configuration setting methods |
57 |
< |
* may only gradually affect actual pool sizes. It is normally best |
58 |
< |
* practice to invoke these methods only when the pool is known to be |
59 |
< |
* quiescent. |
46 |
> |
* processors. The pool attempts to maintain enough active (or |
47 |
> |
* available) threads by dynamically adding, suspending, or resuming |
48 |
> |
* internal worker threads, even if some tasks are stalled waiting to |
49 |
> |
* join others. However, no such adjustments are guaranteed in the |
50 |
> |
* face of blocked IO or other unmanaged synchronization. The nested |
51 |
> |
* {@link ManagedBlocker} interface enables extension of the kinds of |
52 |
> |
* synchronization accommodated. |
53 |
|
* |
54 |
|
* <p>In addition to execution and lifecycle control methods, this |
55 |
|
* class provides status check methods (for example |
58 |
|
* {@link #toString} returns indications of pool state in a |
59 |
|
* convenient form for informal monitoring. |
60 |
|
* |
61 |
+ |
* <p> As is the case with other ExecutorServices, there are three |
62 |
+ |
* main task execution methods summarized in the following table. |
63 |
+ |
* These are designed to be used primarily by clients not already |
64 |
+ |
* engaged in fork/join computations in the current pool. The main |
65 |
+ |
* forms of these methods accept instances of {@code ForkJoinTask}, |
66 |
+ |
* but overloaded forms also allow mixed execution of plain {@code |
67 |
+ |
* Runnable}- or {@code Callable}- based activities as well. However, |
68 |
+ |
* tasks that are already executing in a pool should normally instead |
69 |
+ |
* use the within-computation forms listed in the table unless using |
70 |
+ |
* async event-style tasks that are not usually joined, in which case |
71 |
+ |
* there is little difference among choice of methods. |
72 |
+ |
* |
73 |
+ |
* <table BORDER CELLPADDING=3 CELLSPACING=1> |
74 |
+ |
* <tr> |
75 |
+ |
* <td></td> |
76 |
+ |
* <td ALIGN=CENTER> <b>Call from non-fork/join clients</b></td> |
77 |
+ |
* <td ALIGN=CENTER> <b>Call from within fork/join computations</b></td> |
78 |
+ |
* </tr> |
79 |
+ |
* <tr> |
80 |
+ |
* <td> <b>Arrange async execution</td> |
81 |
+ |
* <td> {@link #execute(ForkJoinTask)}</td> |
82 |
+ |
* <td> {@link ForkJoinTask#fork}</td> |
83 |
+ |
* </tr> |
84 |
+ |
* <tr> |
85 |
+ |
* <td> <b>Await and obtain result</td> |
86 |
+ |
* <td> {@link #invoke(ForkJoinTask)}</td> |
87 |
+ |
* <td> {@link ForkJoinTask#invoke}</td> |
88 |
+ |
* </tr> |
89 |
+ |
* <tr> |
90 |
+ |
* <td> <b>Arrange exec and obtain Future</td> |
91 |
+ |
* <td> {@link #submit(ForkJoinTask)}</td> |
92 |
+ |
* <td> {@link ForkJoinTask#fork} (ForkJoinTasks <em>are</em> Futures)</td> |
93 |
+ |
* </tr> |
94 |
+ |
* </table> |
95 |
+ |
* |
96 |
|
* <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is |
97 |
|
* used for all parallel task execution in a program or subsystem. |
98 |
|
* Otherwise, use would not usually outweigh the construction and |
103 |
|
* daemon} mode, there is typically no need to explicitly {@link |
104 |
|
* #shutdown} such a pool upon program exit. |
105 |
|
* |
106 |
< |
* <pre> |
106 |
> |
* <pre> {@code |
107 |
|
* static final ForkJoinPool mainPool = new ForkJoinPool(); |
108 |
|
* ... |
109 |
|
* public void sort(long[] array) { |
110 |
|
* mainPool.invoke(new SortTask(array, 0, array.length)); |
111 |
< |
* } |
84 |
< |
* </pre> |
111 |
> |
* }}</pre> |
112 |
|
* |
113 |
|
* <p><b>Implementation notes</b>: This implementation restricts the |
114 |
|
* maximum number of running threads to 32767. Attempts to create |
116 |
|
* {@code IllegalArgumentException}. |
117 |
|
* |
118 |
|
* <p>This implementation rejects submitted tasks (that is, by throwing |
119 |
< |
* {@link RejectedExecutionException}) only when the pool is shut down. |
119 |
> |
* {@link RejectedExecutionException}) only when the pool is shut down |
120 |
> |
* or internal resources have been exhausted. |
121 |
|
* |
122 |
|
* @since 1.7 |
123 |
|
* @author Doug Lea |
127 |
|
/* |
128 |
|
* Implementation Overview |
129 |
|
* |
130 |
< |
* This class provides the central bookkeeping and control for a |
131 |
< |
* set of worker threads: Submissions from non-FJ threads enter |
132 |
< |
* into a submission queue. Workers take these tasks and typically |
133 |
< |
* split them into subtasks that may be stolen by other workers. |
134 |
< |
* The main work-stealing mechanics implemented in class |
135 |
< |
* ForkJoinWorkerThread give first priority to processing tasks |
136 |
< |
* from their own queues (LIFO or FIFO, depending on mode), then |
137 |
< |
* to randomized FIFO steals of tasks in other worker queues, and |
138 |
< |
* lastly to new submissions. These mechanics do not consider |
139 |
< |
* affinities, loads, cache localities, etc, so rarely provide the |
140 |
< |
* best possible performance on a given machine, but portably |
141 |
< |
* provide good throughput by averaging over these factors. |
142 |
< |
* (Further, even if we did try to use such information, we do not |
143 |
< |
* usually have a basis for exploiting it. For example, some sets |
144 |
< |
* of tasks profit from cache affinities, but others are harmed by |
145 |
< |
* cache pollution effects.) |
130 |
> |
* This class and its nested classes provide the main |
131 |
> |
* functionality and control for a set of worker threads: |
132 |
> |
* Submissions from non-FJ threads enter into submission queues. |
133 |
> |
* Workers take these tasks and typically split them into subtasks |
134 |
> |
* that may be stolen by other workers. Preference rules give |
135 |
> |
* first priority to processing tasks from their own queues (LIFO |
136 |
> |
* or FIFO, depending on mode), then to randomized FIFO steals of |
137 |
> |
* tasks in other queues. |
138 |
> |
* |
139 |
> |
* WorkQueues |
140 |
> |
* ========== |
141 |
> |
* |
142 |
> |
* Most operations occur within work-stealing queues (in nested |
143 |
> |
* class WorkQueue). These are special forms of Deques that |
144 |
> |
* support only three of the four possible end-operations -- push, |
145 |
> |
* pop, and poll (aka steal), under the further constraints that |
146 |
> |
* push and pop are called only from the owning thread (or, as |
147 |
> |
* extended here, under a lock), while poll may be called from |
148 |
> |
* other threads. (If you are unfamiliar with them, you probably |
149 |
> |
* want to read Herlihy and Shavit's book "The Art of |
150 |
> |
* Multiprocessor programming", chapter 16 describing these in |
151 |
> |
* more detail before proceeding.) The main work-stealing queue |
152 |
> |
* design is roughly similar to those in the papers "Dynamic |
153 |
> |
* Circular Work-Stealing Deque" by Chase and Lev, SPAA 2005 |
154 |
> |
* (http://research.sun.com/scalable/pubs/index.html) and |
155 |
> |
* "Idempotent work stealing" by Michael, Saraswat, and Vechev, |
156 |
> |
* PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186). |
157 |
> |
* The main differences ultimately stem from GC requirements that |
158 |
> |
* we null out taken slots as soon as we can, to maintain as small |
159 |
> |
* a footprint as possible even in programs generating huge |
160 |
> |
* numbers of tasks. To accomplish this, we shift the CAS |
161 |
> |
* arbitrating pop vs poll (steal) from being on the indices |
162 |
> |
* ("base" and "top") to the slots themselves. So, both a |
163 |
> |
* successful pop and poll mainly entail a CAS of a slot from |
164 |
> |
* non-null to null. Because we rely on CASes of references, we |
165 |
> |
* do not need tag bits on base or top. They are simple ints as |
166 |
> |
* used in any circular array-based queue (see for example |
167 |
> |
* ArrayDeque). Updates to the indices must still be ordered in a |
168 |
> |
* way that guarantees that top == base means the queue is empty, |
169 |
> |
* but otherwise may err on the side of possibly making the queue |
170 |
> |
* appear nonempty when a push, pop, or poll have not fully |
171 |
> |
* committed. Note that this means that the poll operation, |
172 |
> |
* considered individually, is not wait-free. One thief cannot |
173 |
> |
* successfully continue until another in-progress one (or, if |
174 |
> |
* previously empty, a push) completes. However, in the |
175 |
> |
* aggregate, we ensure at least probabilistic non-blockingness. |
176 |
> |
* If an attempted steal fails, a thief always chooses a different |
177 |
> |
* random victim target to try next. So, in order for one thief to |
178 |
> |
* progress, it suffices for any in-progress poll or new push on |
179 |
> |
* any empty queue to complete. (This is why we normally use |
180 |
> |
* method pollAt and its variants that try once at the apparent |
181 |
> |
* base index, else consider alternative actions, rather than |
182 |
> |
* method poll.) |
183 |
> |
* |
184 |
> |
* This approach also enables support of a user mode in which local |
185 |
> |
* task processing is in FIFO, not LIFO order, simply by using |
186 |
> |
* poll rather than pop. This can be useful in message-passing |
187 |
> |
* frameworks in which tasks are never joined. However neither |
188 |
> |
* mode considers affinities, loads, cache localities, etc, so |
189 |
> |
* rarely provide the best possible performance on a given |
190 |
> |
* machine, but portably provide good throughput by averaging over |
191 |
> |
* these factors. (Further, even if we did try to use such |
192 |
> |
* information, we do not usually have a basis for exploiting it. |
193 |
> |
* For example, some sets of tasks profit from cache affinities, |
194 |
> |
* but others are harmed by cache pollution effects.) |
195 |
> |
* |
196 |
> |
* WorkQueues are also used in a similar way for tasks submitted |
197 |
> |
* to the pool. We cannot mix these tasks in the same queues used |
198 |
> |
* for work-stealing (this would contaminate lifo/fifo |
199 |
> |
* processing). Instead, we loosely associate submission queues |
200 |
> |
* with submitting threads, using a form of hashing. The |
201 |
> |
* ThreadLocal Submitter class contains a value initially used as |
202 |
> |
* a hash code for choosing existing queues, but may be randomly |
203 |
> |
* repositioned upon contention with other submitters. In |
204 |
> |
* essence, submitters act like workers except that they never |
205 |
> |
* take tasks, and they are multiplexed on to a finite number of |
206 |
> |
* shared work queues. However, classes are set up so that future |
207 |
> |
* extensions could allow submitters to optionally help perform |
208 |
> |
* tasks as well. Insertion of tasks in shared mode requires a |
209 |
> |
* lock (mainly to protect in the case of resizing) but we use |
210 |
> |
* only a simple spinlock (using bits in field runState), because |
211 |
> |
* submitters encountering a busy queue move on to try or create |
212 |
> |
* other queues -- they block only when creating and registering |
213 |
> |
* new queues. |
214 |
> |
* |
215 |
> |
* Management |
216 |
> |
* ========== |
217 |
|
* |
218 |
|
* The main throughput advantages of work-stealing stem from |
219 |
< |
* decentralized control -- workers mostly steal tasks from each |
220 |
< |
* other. We do not want to negate this by creating bottlenecks |
221 |
< |
* implementing the management responsibilities of this class. So |
222 |
< |
* we use a collection of techniques that avoid, reduce, or cope |
223 |
< |
* well with contention. These entail several instances of |
224 |
< |
* bit-packing into CASable fields to maintain only the minimally |
225 |
< |
* required atomicity. To enable such packing, we restrict maximum |
226 |
< |
* parallelism to (1<<15)-1 (enabling twice this to fit into a 16 |
227 |
< |
* bit field), which is far in excess of normal operating range. |
228 |
< |
* Even though updates to some of these bookkeeping fields do |
229 |
< |
* sometimes contend with each other, they don't normally |
230 |
< |
* cache-contend with updates to others enough to warrant memory |
231 |
< |
* padding or isolation. So they are all held as fields of |
232 |
< |
* ForkJoinPool objects. The main capabilities are as follows: |
233 |
< |
* |
234 |
< |
* 1. Creating and removing workers. Workers are recorded in the |
235 |
< |
* "workers" array. This is an array as opposed to some other data |
236 |
< |
* structure to support index-based random steals by workers. |
237 |
< |
* Updates to the array recording new workers and unrecording |
238 |
< |
* terminated ones are protected from each other by a lock |
239 |
< |
* (workerLock) but the array is otherwise concurrently readable, |
240 |
< |
* and accessed directly by workers. To simplify index-based |
219 |
> |
* decentralized control -- workers mostly take tasks from |
220 |
> |
* themselves or each other. We cannot negate this in the |
221 |
> |
* implementation of other management responsibilities. The main |
222 |
> |
* tactic for avoiding bottlenecks is packing nearly all |
223 |
> |
* essentially atomic control state into two volatile variables |
224 |
> |
* that are by far most often read (not written) as status and |
225 |
> |
* consistency checks. |
226 |
> |
* |
227 |
> |
* Field "ctl" contains 64 bits holding all the information needed |
228 |
> |
* to atomically decide to add, inactivate, enqueue (on an event |
229 |
> |
* queue), dequeue, and/or re-activate workers. To enable this |
230 |
> |
* packing, we restrict maximum parallelism to (1<<15)-1 (which is |
231 |
> |
* far in excess of normal operating range) to allow ids, counts, |
232 |
> |
* and their negations (used for thresholding) to fit into 16bit |
233 |
> |
* fields. |
234 |
> |
* |
235 |
> |
* Field "runState" contains 32 bits needed to register and |
236 |
> |
* deregister WorkQueues, as well as to enable shutdown. It is |
237 |
> |
* only modified under a lock (normally briefly held, but |
238 |
> |
* occasionally protecting allocations and resizings) but even |
239 |
> |
* when locked remains available to check consistency. |
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. Currently, all but the first |
249 |
< |
* worker thread creation is on-demand, triggered by task |
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. |
252 |
> |
* |
253 |
> |
* All worker thread creation is on-demand, triggered by task |
254 |
|
* submissions, replacement of terminated workers, and/or |
255 |
|
* compensation for blocked workers. However, all other support |
256 |
< |
* code is set up to work with other policies. |
257 |
< |
* |
258 |
< |
* 2. Bookkeeping for dynamically adding and removing workers. We |
259 |
< |
* maintain a given level of parallelism (or, if |
260 |
< |
* maintainsParallelism is false, at least avoid starvation). When |
261 |
< |
* some workers are known to be blocked (on joins or via |
262 |
< |
* ManagedBlocker), we may create or resume others to take their |
263 |
< |
* place until they unblock (see below). Implementing this |
264 |
< |
* requires counts of the number of "running" threads (i.e., those |
265 |
< |
* that are neither blocked nor artifically suspended) as well as |
266 |
< |
* the total number. These two values are packed into one field, |
267 |
< |
* "workerCounts" because we need accurate snapshots when deciding |
268 |
< |
* to create, resume or suspend. To support these decisions, |
269 |
< |
* updates must be prospective (not retrospective). For example, |
270 |
< |
* the running count is decremented before blocking by a thread |
271 |
< |
* about to block, but incremented by the thread about to unblock |
272 |
< |
* it. (In a few cases, these prospective updates may need to be |
273 |
< |
* rolled back, for example when deciding to create a new worker |
274 |
< |
* but the thread factory fails or returns null. In these cases, |
275 |
< |
* we are no worse off wrt other decisions than we would be |
276 |
< |
* otherwise.) Updates to the workerCounts field sometimes |
277 |
< |
* transiently encounter a fair amount of contention when join |
278 |
< |
* dependencies are such that many threads block or unblock at |
279 |
< |
* about the same time. We alleviate this by sometimes bundling |
280 |
< |
* updates (for example blocking one thread on join and resuming a |
281 |
< |
* spare cancel each other out), and in most other cases |
282 |
< |
* performing an alternative action (like releasing waiters and |
283 |
< |
* finding spares; see below) as a more productive form of |
284 |
< |
* backoff. |
285 |
< |
* |
286 |
< |
* 3. Maintaining global run state. The run state of the pool |
287 |
< |
* consists of a runLevel (SHUTDOWN, TERMINATING, etc) similar to |
288 |
< |
* those in other Executor implementations, as well as a count of |
289 |
< |
* "active" workers -- those that are, or soon will be, or |
290 |
< |
* recently were executing tasks. The runLevel and active count |
291 |
< |
* are packed together in order to correctly trigger shutdown and |
292 |
< |
* termination. Without care, active counts can be subject to very |
293 |
< |
* high contention. We substantially reduce this contention by |
294 |
< |
* relaxing update rules. A worker must claim active status |
295 |
< |
* prospectively, by activating if it sees that a submitted or |
296 |
< |
* stealable task exists (it may find after activating that the |
297 |
< |
* task no longer exists). It stays active while processing this |
298 |
< |
* task (if it exists) and any other local subtasks it produces, |
299 |
< |
* until it cannot find any other tasks. It then tries |
300 |
< |
* inactivating (see method preStep), but upon update contention |
301 |
< |
* instead scans for more tasks, later retrying inactivation if it |
302 |
< |
* doesn't find any. |
303 |
< |
* |
304 |
< |
* 4. Managing idle workers waiting for tasks. We cannot let |
305 |
< |
* workers spin indefinitely scanning for tasks when none are |
306 |
< |
* available. On the other hand, we must quickly prod them into |
307 |
< |
* action when new tasks are submitted or generated. We |
308 |
< |
* park/unpark these idle workers using an event-count scheme. |
309 |
< |
* Field eventCount is incremented upon events that may enable |
310 |
< |
* workers that previously could not find a task to now find one: |
311 |
< |
* Submission of a new task to the pool, or another worker pushing |
312 |
< |
* a task onto a previously empty queue. (We also use this |
313 |
< |
* mechanism for termination and reconfiguration actions that |
314 |
< |
* require wakeups of idle workers). Each worker maintains its |
315 |
< |
* last known event count, and blocks when a scan for work did not |
316 |
< |
* find a task AND its lastEventCount matches the current |
317 |
< |
* eventCount. Waiting idle workers are recorded in a variant of |
318 |
< |
* Treiber stack headed by field eventWaiters which, when nonzero, |
319 |
< |
* encodes the thread index and count awaited for by the worker |
320 |
< |
* thread most recently calling eventSync. This thread in turn has |
321 |
< |
* a record (field nextEventWaiter) for the next waiting worker. |
322 |
< |
* In addition to allowing simpler decisions about need for |
323 |
< |
* wakeup, the event count bits in eventWaiters serve the role of |
324 |
< |
* tags to avoid ABA errors in Treiber stacks. To reduce delays |
325 |
< |
* in task diffusion, workers not otherwise occupied may invoke |
326 |
< |
* method releaseWaiters, that removes and signals (unparks) |
327 |
< |
* workers not waiting on current count. To minimize task |
328 |
< |
* production stalls associate with signalling, any worker pushing |
329 |
< |
* a task on an empty queue invokes the weaker method signalWork, |
330 |
< |
* that only releases idle workers until it detects interference |
331 |
< |
* by other threads trying to release, and lets them take |
332 |
< |
* over. The net effect is a tree-like diffusion of signals, where |
333 |
< |
* released threads and possibly others) help with unparks. To |
334 |
< |
* further reduce contention effects a bit, failed CASes to |
335 |
< |
* increment field eventCount are tolerated without retries. |
336 |
< |
* Conceptually they are merged into the same event, which is OK |
337 |
< |
* when their only purpose is to enable workers to scan for work. |
338 |
< |
* |
339 |
< |
* 5. Managing suspension of extra workers. When a worker is about |
340 |
< |
* to block waiting for a join (or via ManagedBlockers), we may |
341 |
< |
* create a new thread to maintain parallelism level, or at least |
342 |
< |
* avoid starvation (see below). Usually, extra threads are needed |
343 |
< |
* for only very short periods, yet join dependencies are such |
344 |
< |
* that we sometimes need them in bursts. Rather than create new |
345 |
< |
* threads each time this happens, we suspend no-longer-needed |
346 |
< |
* extra ones as "spares". For most purposes, we don't distinguish |
347 |
< |
* "extra" spare threads from normal "core" threads: On each call |
348 |
< |
* to preStep (the only point at which we can do this) a worker |
349 |
< |
* checks to see if there are now too many running workers, and if |
350 |
< |
* so, suspends itself. Methods preJoin and doBlock look for |
351 |
< |
* suspended threads to resume before considering creating a new |
352 |
< |
* replacement. We don't need a special data structure to maintain |
353 |
< |
* spares; simply scanning the workers array looking for |
354 |
< |
* worker.isSuspended() is fine because the calling thread is |
355 |
< |
* otherwise not doing anything useful anyway; we are at least as |
356 |
< |
* happy if after locating a spare, the caller doesn't actually |
357 |
< |
* block because the join is ready before we try to adjust and |
358 |
< |
* compensate. Note that this is intrinsically racy. One thread |
359 |
< |
* may become a spare at about the same time as another is |
360 |
< |
* needlessly being created. We counteract this and related slop |
361 |
< |
* in part by requiring resumed spares to immediately recheck (in |
362 |
< |
* preStep) to see whether they they should re-suspend. The only |
363 |
< |
* effective difference between "extra" and "core" threads is that |
364 |
< |
* we allow the "extra" ones to time out and die if they are not |
365 |
< |
* resumed within a keep-alive interval of a few seconds. This is |
366 |
< |
* implemented mainly within ForkJoinWorkerThread, but requires |
367 |
< |
* some coordination (isTrimmed() -- meaning killed while |
368 |
< |
* suspended) to correctly maintain pool counts. |
369 |
< |
* |
370 |
< |
* 6. Deciding when to create new workers. The main dynamic |
371 |
< |
* control in this class is deciding when to create extra threads, |
372 |
< |
* in methods preJoin and doBlock. We always need to create one |
373 |
< |
* when the number of running threads becomes zero. But because |
374 |
< |
* blocked joins are typically dependent, we don't necessarily |
375 |
< |
* need or want one-to-one replacement. Using a one-to-one |
376 |
< |
* compensation rule often leads to enough useless overhead |
377 |
< |
* creating, suspending, resuming, and/or killing threads to |
378 |
< |
* signficantly degrade throughput. We use a rule reflecting the |
379 |
< |
* idea that, the more spare threads you already have, the more |
380 |
< |
* evidence you need to create another one; where "evidence" is |
381 |
< |
* expressed as the current deficit -- target minus running |
382 |
< |
* threads. To reduce flickering and drift around target values, |
383 |
< |
* the relation is quadratic: adding a spare if (dc*dc)>=(sc*pc) |
384 |
< |
* (where dc is deficit, sc is number of spare threads and pc is |
385 |
< |
* target parallelism.) This effectively reduces churn at the |
386 |
< |
* price of systematically undershooting target parallelism when |
387 |
< |
* many threads are blocked. However, biasing toward undeshooting |
388 |
< |
* partially compensates for the above mechanics to suspend extra |
389 |
< |
* threads, that normally lead to overshoot because we can only |
390 |
< |
* suspend workers in-between top-level actions. It also better |
391 |
< |
* copes with the fact that some of the methods in this class tend |
392 |
< |
* to never become compiled (but are interpreted), so some |
393 |
< |
* components of the entire set of controls might execute many |
394 |
< |
* times faster than others. And similarly for cases where the |
395 |
< |
* apparent lack of work is just due to GC stalls and other |
396 |
< |
* transient system activity. |
397 |
< |
* |
398 |
< |
* 7. Maintaining other configuration parameters and monitoring |
399 |
< |
* statistics. Updates to fields controlling parallelism level, |
400 |
< |
* max size, etc can only meaningfully take effect for individual |
401 |
< |
* threads upon their next top-level actions; i.e., between |
402 |
< |
* stealing/running tasks/submission, which are separated by calls |
403 |
< |
* to preStep. Memory ordering for these (assumed infrequent) |
404 |
< |
* reconfiguration calls is ensured by using reads and writes to |
405 |
< |
* volatile field workerCounts (that must be read in preStep anyway) |
406 |
< |
* as "fences" -- user-level reads are preceded by reads of |
407 |
< |
* workCounts, and writes are followed by no-op CAS to |
408 |
< |
* workerCounts. The values reported by other management and |
409 |
< |
* monitoring methods are either computed on demand, or are kept |
410 |
< |
* in fields that are only updated when threads are otherwise |
411 |
< |
* idle. |
256 |
> |
* code is set up to work with other policies. To ensure that we |
257 |
> |
* do not hold on to worker references that would prevent GC, ALL |
258 |
> |
* accesses to workQueues are via indices into the workQueues |
259 |
> |
* array (which is one source of some of the messy code |
260 |
> |
* constructions here). In essence, the workQueues array serves as |
261 |
> |
* a weak reference mechanism. Thus for example the wait queue |
262 |
> |
* field of ctl stores indices, not references. Access to the |
263 |
> |
* workQueues in associated methods (for example signalWork) must |
264 |
> |
* both index-check and null-check the IDs. All such accesses |
265 |
> |
* ignore bad IDs by returning out early from what they are doing, |
266 |
> |
* since this can only be associated with termination, in which |
267 |
> |
* case it is OK to give up. All uses of the workQueues array |
268 |
> |
* also check that it is non-null (even if previously |
269 |
> |
* non-null). This allows nulling during termination, which is |
270 |
> |
* currently not necessary, but remains an option for |
271 |
> |
* resource-revocation-based shutdown schemes. It also helps |
272 |
> |
* reduce JIT issuance of uncommon-trap code, which tends to |
273 |
> |
* unnecessarily complicate control flow in some methods. |
274 |
> |
* |
275 |
> |
* Event Queuing. Unlike HPC work-stealing frameworks, we cannot |
276 |
> |
* let workers spin indefinitely scanning for tasks when none can |
277 |
> |
* be found immediately, and we cannot start/resume workers unless |
278 |
> |
* there appear to be tasks available. On the other hand, we must |
279 |
> |
* quickly prod them into action when new tasks are submitted or |
280 |
> |
* generated. In many usages, ramp-up time to activate workers is |
281 |
> |
* the main limiting factor in overall performance (this is |
282 |
> |
* compounded at program start-up by JIT compilation and |
283 |
> |
* allocation). So we try to streamline this as much as possible. |
284 |
> |
* We park/unpark workers after placing in an event wait queue |
285 |
> |
* when they cannot find work. This "queue" is actually a simple |
286 |
> |
* Treiber stack, headed by the "id" field of ctl, plus a 15bit |
287 |
> |
* counter value (that reflects the number of times a worker has |
288 |
> |
* been inactivated) to avoid ABA effects (we need only as many |
289 |
> |
* version numbers as worker threads). Successors are held in |
290 |
> |
* field WorkQueue.nextWait. Queuing deals with several intrinsic |
291 |
> |
* races, mainly that a task-producing thread can miss seeing (and |
292 |
> |
* signalling) another thread that gave up looking for work but |
293 |
> |
* has not yet entered the wait queue. We solve this by requiring |
294 |
> |
* a full sweep of all workers (via repeated calls to method |
295 |
> |
* scan()) both before and after a newly waiting worker is added |
296 |
> |
* to the wait queue. During a rescan, the worker might release |
297 |
> |
* some other queued worker rather than itself, which has the same |
298 |
> |
* net effect. Because enqueued workers may actually be rescanning |
299 |
> |
* rather than waiting, we set and clear the "parker" field of |
300 |
> |
* WorkQueues to reduce unnecessary calls to unpark. (This |
301 |
> |
* requires a secondary recheck to avoid missed signals.) Note |
302 |
> |
* the unusual conventions about Thread.interrupts surrounding |
303 |
> |
* parking and other blocking: Because interrupts are used solely |
304 |
> |
* to alert threads to check termination, which is checked anyway |
305 |
> |
* upon blocking, we clear status (using Thread.interrupted) |
306 |
> |
* before any call to park, so that park does not immediately |
307 |
> |
* return due to status being set via some other unrelated call to |
308 |
> |
* interrupt in user code. |
309 |
> |
* |
310 |
> |
* Signalling. We create or wake up workers only when there |
311 |
> |
* appears to be at least one task they might be able to find and |
312 |
> |
* execute. When a submission is added or another worker adds a |
313 |
> |
* task to a queue that previously had fewer than two tasks, they |
314 |
> |
* signal waiting workers (or trigger creation of new ones if |
315 |
> |
* fewer than the given parallelism level -- see signalWork). |
316 |
> |
* These primary signals are buttressed by signals during rescans; |
317 |
> |
* together these cover the signals needed in cases when more |
318 |
> |
* tasks are pushed but untaken, and improve performance compared |
319 |
> |
* to having one thread wake up all workers. |
320 |
> |
* |
321 |
> |
* Trimming workers. To release resources after periods of lack of |
322 |
> |
* use, a worker starting to wait when the pool is quiescent will |
323 |
> |
* time out and terminate if the pool has remained quiescent for |
324 |
> |
* SHRINK_RATE nanosecs. This will slowly propagate, eventually |
325 |
> |
* terminating all workers after long periods of non-use. |
326 |
> |
* |
327 |
> |
* Shutdown and Termination. A call to shutdownNow atomically sets |
328 |
> |
* a runState bit and then (non-atomically) sets each worker's |
329 |
> |
* runState status, cancels all unprocessed tasks, and wakes up |
330 |
> |
* all waiting workers. Detecting whether termination should |
331 |
> |
* commence after a non-abrupt shutdown() call requires more work |
332 |
> |
* and bookkeeping. We need consensus about quiescence (i.e., that |
333 |
> |
* there is no more work). The active count provides a primary |
334 |
> |
* indication but non-abrupt shutdown still requires a rechecking |
335 |
> |
* scan for any workers that are inactive but not queued. |
336 |
> |
* |
337 |
> |
* Joining Tasks |
338 |
> |
* ============= |
339 |
> |
* |
340 |
> |
* Any of several actions may be taken when one worker is waiting |
341 |
> |
* to join a task stolen (or always held) by another. Because we |
342 |
> |
* are multiplexing many tasks on to a pool of workers, we can't |
343 |
> |
* just let them block (as in Thread.join). We also cannot just |
344 |
> |
* reassign the joiner's run-time stack with another and replace |
345 |
> |
* it later, which would be a form of "continuation", that even if |
346 |
> |
* possible is not necessarily a good idea since we sometimes need |
347 |
> |
* both an unblocked task and its continuation to progress. |
348 |
> |
* Instead we combine two tactics: |
349 |
> |
* |
350 |
> |
* Helping: Arranging for the joiner to execute some task that it |
351 |
> |
* would be running if the steal had not occurred. |
352 |
> |
* |
353 |
> |
* Compensating: Unless there are already enough live threads, |
354 |
> |
* method tryCompensate() may create or re-activate a spare |
355 |
> |
* thread to compensate for blocked joiners until they unblock. |
356 |
> |
* |
357 |
> |
* A third form (implemented in tryRemoveAndExec and |
358 |
> |
* tryPollForAndExec) amounts to helping a hypothetical |
359 |
> |
* compensator: If we can readily tell that a possible action of a |
360 |
> |
* compensator is to steal and execute the task being joined, the |
361 |
> |
* joining thread can do so directly, without the need for a |
362 |
> |
* compensation thread (although at the expense of larger run-time |
363 |
> |
* stacks, but the tradeoff is typically worthwhile). |
364 |
> |
* |
365 |
> |
* The ManagedBlocker extension API can't use helping so relies |
366 |
> |
* only on compensation in method awaitBlocker. |
367 |
> |
* |
368 |
> |
* The algorithm in tryHelpStealer entails a form of "linear" |
369 |
> |
* helping: Each worker records (in field currentSteal) the most |
370 |
> |
* recent task it stole from some other worker. Plus, it records |
371 |
> |
* (in field currentJoin) the task it is currently actively |
372 |
> |
* joining. Method tryHelpStealer uses these markers to try to |
373 |
> |
* find a worker to help (i.e., steal back a task from and execute |
374 |
> |
* it) that could hasten completion of the actively joined task. |
375 |
> |
* In essence, the joiner executes a task that would be on its own |
376 |
> |
* local deque had the to-be-joined task not been stolen. This may |
377 |
> |
* be seen as a conservative variant of the approach in Wagner & |
378 |
> |
* Calder "Leapfrogging: a portable technique for implementing |
379 |
> |
* efficient futures" SIGPLAN Notices, 1993 |
380 |
> |
* (http://portal.acm.org/citation.cfm?id=155354). It differs in |
381 |
> |
* that: (1) We only maintain dependency links across workers upon |
382 |
> |
* steals, rather than use per-task bookkeeping. This sometimes |
383 |
> |
* requires a linear scan of workQueues array to locate stealers, |
384 |
> |
* but often doesn't because stealers leave hints (that may become |
385 |
> |
* stale/wrong) of where to locate them. A stealHint is only a |
386 |
> |
* hint because a worker might have had multiple steals and the |
387 |
> |
* hint records only one of them (usually the most current). |
388 |
> |
* Hinting isolates cost to when it is needed, rather than adding |
389 |
> |
* to per-task overhead. (2) It is "shallow", ignoring nesting |
390 |
> |
* and potentially cyclic mutual steals. (3) It is intentionally |
391 |
> |
* racy: field currentJoin is updated only while actively joining, |
392 |
> |
* which means that we miss links in the chain during long-lived |
393 |
> |
* tasks, GC stalls etc (which is OK since blocking in such cases |
394 |
> |
* is usually a good idea). (4) We bound the number of attempts |
395 |
> |
* to find work (see MAX_HELP) and fall back to suspending the |
396 |
> |
* worker and if necessary replacing it with another. |
397 |
> |
* |
398 |
> |
* It is impossible to keep exactly the target parallelism number |
399 |
> |
* of threads running at any given time. Determining the |
400 |
> |
* existence of conservatively safe helping targets, the |
401 |
> |
* availability of already-created spares, and the apparent need |
402 |
> |
* to create new spares are all racy, so we rely on multiple |
403 |
> |
* retries of each. Compensation in the apparent absence of |
404 |
> |
* helping opportunities is challenging to control on JVMs, where |
405 |
> |
* GC and other activities can stall progress of tasks that in |
406 |
> |
* turn stall out many other dependent tasks, without us being |
407 |
> |
* able to determine whether they will ever require compensation. |
408 |
> |
* Even though work-stealing otherwise encounters little |
409 |
> |
* degradation in the presence of more threads than cores, |
410 |
> |
* aggressively adding new threads in such cases entails risk of |
411 |
> |
* unwanted positive feedback control loops in which more threads |
412 |
> |
* cause more dependent stalls (as well as delayed progress of |
413 |
> |
* unblocked threads to the point that we know they are available) |
414 |
> |
* leading to more situations requiring more threads, and so |
415 |
> |
* on. This aspect of control can be seen as an (analytically |
416 |
> |
* intractable) game with an opponent that may choose the worst |
417 |
> |
* (for us) active thread to stall at any time. We take several |
418 |
> |
* precautions to bound losses (and thus bound gains), mainly in |
419 |
> |
* methods tryCompensate and awaitJoin: (1) We only try |
420 |
> |
* compensation after attempting enough helping steps (measured |
421 |
> |
* via counting and timing) that we have already consumed the |
422 |
> |
* estimated cost of creating and activating a new thread. (2) We |
423 |
> |
* allow up to 50% of threads to be blocked before initially |
424 |
> |
* adding any others, and unless completely saturated, check that |
425 |
> |
* some work is available for a new worker before adding. Also, we |
426 |
> |
* create up to only 50% more threads until entering a mode that |
427 |
> |
* only adds a thread if all others are possibly blocked. All |
428 |
> |
* together, this means that we might be half as fast to react, |
429 |
> |
* and create half as many threads as possible in the ideal case, |
430 |
> |
* but present vastly fewer anomalies in all other cases compared |
431 |
> |
* to both more aggressive and more conservative alternatives. |
432 |
|
* |
433 |
< |
* Beware that there is a lot of representation-level coupling |
433 |
> |
* Style notes: There is a lot of representation-level coupling |
434 |
|
* among classes ForkJoinPool, ForkJoinWorkerThread, and |
435 |
< |
* ForkJoinTask. For example, direct access to "workers" array by |
436 |
< |
* workers, and direct access to ForkJoinTask.status by both |
437 |
< |
* ForkJoinPool and ForkJoinWorkerThread. There is little point |
438 |
< |
* trying to reduce this, since any associated future changes in |
439 |
< |
* representations will need to be accompanied by algorithmic |
440 |
< |
* changes anyway. |
441 |
< |
* |
442 |
< |
* Style notes: There are lots of inline assignments (of form |
443 |
< |
* "while ((local = field) != 0)") which are usually the simplest |
444 |
< |
* way to ensure read orderings. Also several occurrences of the |
445 |
< |
* unusual "do {} while(!cas...)" which is the simplest way to |
446 |
< |
* force an update of a CAS'ed variable. There are also a few |
447 |
< |
* other coding oddities that help some methods perform reasonably |
448 |
< |
* even when interpreted (not compiled). |
449 |
< |
* |
450 |
< |
* The order of declarations in this file is: (1) statics (2) |
451 |
< |
* fields (along with constants used when unpacking some of them) |
452 |
< |
* (3) internal control methods (4) callbacks and other support |
453 |
< |
* for ForkJoinTask and ForkJoinWorkerThread classes, (5) exported |
454 |
< |
* methods (plus a few little helpers). |
435 |
> |
* ForkJoinTask. The fields of WorkQueue maintain data structures |
436 |
> |
* managed by ForkJoinPool, so are directly accessed. There is |
437 |
> |
* little point trying to reduce this, since any associated future |
438 |
> |
* changes in representations will need to be accompanied by |
439 |
> |
* algorithmic changes anyway. Several methods intrinsically |
440 |
> |
* sprawl because they must accumulate sets of consistent reads of |
441 |
> |
* volatiles held in local variables. Methods signalWork() and |
442 |
> |
* scan() are the main bottlenecks, so are especially heavily |
443 |
> |
* micro-optimized/mangled. There are lots of inline assignments |
444 |
> |
* (of form "while ((local = field) != 0)") which are usually the |
445 |
> |
* simplest way to ensure the required read orderings (which are |
446 |
> |
* sometimes critical). This leads to a "C"-like style of listing |
447 |
> |
* declarations of these locals at the heads of methods or blocks. |
448 |
> |
* There are several occurrences of the unusual "do {} while |
449 |
> |
* (!cas...)" which is the simplest way to force an update of a |
450 |
> |
* CAS'ed variable. There are also other coding oddities that help |
451 |
> |
* some methods perform reasonably even when interpreted (not |
452 |
> |
* compiled). |
453 |
> |
* |
454 |
> |
* The order of declarations in this file is: |
455 |
> |
* (1) Static utility functions |
456 |
> |
* (2) Nested (static) classes |
457 |
> |
* (3) Static fields |
458 |
> |
* (4) Fields, along with constants used when unpacking some of them |
459 |
> |
* (5) Internal control methods |
460 |
> |
* (6) Callbacks and other support for ForkJoinTask methods |
461 |
> |
* (7) Exported methods |
462 |
> |
* (8) Static block initializing statics in minimally dependent order |
463 |
|
*/ |
464 |
|
|
465 |
+ |
// Static utilities |
466 |
+ |
|
467 |
+ |
/** |
468 |
+ |
* If there is a security manager, makes sure caller has |
469 |
+ |
* permission to modify threads. |
470 |
+ |
*/ |
471 |
+ |
private static void checkPermission() { |
472 |
+ |
SecurityManager security = System.getSecurityManager(); |
473 |
+ |
if (security != null) |
474 |
+ |
security.checkPermission(modifyThreadPermission); |
475 |
+ |
} |
476 |
+ |
|
477 |
+ |
// Nested classes |
478 |
+ |
|
479 |
|
/** |
480 |
|
* Factory for creating new {@link ForkJoinWorkerThread}s. |
481 |
|
* A {@code ForkJoinWorkerThreadFactory} must be defined and used |
496 |
|
* Default ForkJoinWorkerThreadFactory implementation; creates a |
497 |
|
* new ForkJoinWorkerThread. |
498 |
|
*/ |
499 |
< |
static class DefaultForkJoinWorkerThreadFactory |
499 |
> |
static class DefaultForkJoinWorkerThreadFactory |
500 |
|
implements ForkJoinWorkerThreadFactory { |
501 |
|
public ForkJoinWorkerThread newThread(ForkJoinPool pool) { |
502 |
|
return new ForkJoinWorkerThread(pool); |
504 |
|
} |
505 |
|
|
506 |
|
/** |
507 |
< |
* Creates a new ForkJoinWorkerThread. This factory is used unless |
508 |
< |
* overridden in ForkJoinPool constructors. |
507 |
> |
* A simple non-reentrant lock used for exclusion when managing |
508 |
> |
* queues and workers. We use a custom lock so that we can readily |
509 |
> |
* probe lock state in constructions that check among alternative |
510 |
> |
* actions. The lock is normally only very briefly held, and |
511 |
> |
* sometimes treated as a spinlock, but other usages block to |
512 |
> |
* reduce overall contention in those cases where locked code |
513 |
> |
* bodies perform allocation/resizing. |
514 |
> |
*/ |
515 |
> |
static final class Mutex extends AbstractQueuedSynchronizer { |
516 |
> |
public final boolean tryAcquire(int ignore) { |
517 |
> |
return compareAndSetState(0, 1); |
518 |
> |
} |
519 |
> |
public final boolean tryRelease(int ignore) { |
520 |
> |
setState(0); |
521 |
> |
return true; |
522 |
> |
} |
523 |
> |
public final void lock() { acquire(0); } |
524 |
> |
public final void unlock() { release(0); } |
525 |
> |
public final boolean isHeldExclusively() { return getState() == 1; } |
526 |
> |
public final Condition newCondition() { return new ConditionObject(); } |
527 |
> |
} |
528 |
> |
|
529 |
> |
/** |
530 |
> |
* Class for artificial tasks that are used to replace the target |
531 |
> |
* of local joins if they are removed from an interior queue slot |
532 |
> |
* in WorkQueue.tryRemoveAndExec. We don't need the proxy to |
533 |
> |
* actually do anything beyond having a unique identity. |
534 |
> |
*/ |
535 |
> |
static final class EmptyTask extends ForkJoinTask<Void> { |
536 |
> |
EmptyTask() { status = ForkJoinTask.NORMAL; } // force done |
537 |
> |
public final Void getRawResult() { return null; } |
538 |
> |
public final void setRawResult(Void x) {} |
539 |
> |
public final boolean exec() { return true; } |
540 |
> |
} |
541 |
> |
|
542 |
> |
/** |
543 |
> |
* Queues supporting work-stealing as well as external task |
544 |
> |
* submission. See above for main rationale and algorithms. |
545 |
> |
* Implementation relies heavily on "Unsafe" intrinsics |
546 |
> |
* and selective use of "volatile": |
547 |
> |
* |
548 |
> |
* Field "base" is the index (mod array.length) of the least valid |
549 |
> |
* queue slot, which is always the next position to steal (poll) |
550 |
> |
* from if nonempty. Reads and writes require volatile orderings |
551 |
> |
* but not CAS, because updates are only performed after slot |
552 |
> |
* CASes. |
553 |
> |
* |
554 |
> |
* Field "top" is the index (mod array.length) of the next queue |
555 |
> |
* slot to push to or pop from. It is written only by owner thread |
556 |
> |
* for push, or under lock for trySharedPush, and accessed by |
557 |
> |
* other threads only after reading (volatile) base. Both top and |
558 |
> |
* base are allowed to wrap around on overflow, but (top - base) |
559 |
> |
* (or more commonly -(base - top) to force volatile read of base |
560 |
> |
* before top) still estimates size. |
561 |
> |
* |
562 |
> |
* The array slots are read and written using the emulation of |
563 |
> |
* volatiles/atomics provided by Unsafe. Insertions must in |
564 |
> |
* general use putOrderedObject as a form of releasing store to |
565 |
> |
* ensure that all writes to the task object are ordered before |
566 |
> |
* its publication in the queue. (Although we can avoid one case |
567 |
> |
* of this when locked in trySharedPush.) All removals entail a |
568 |
> |
* CAS to null. The array is always a power of two. To ensure |
569 |
> |
* safety of Unsafe array operations, all accesses perform |
570 |
> |
* explicit null checks and implicit bounds checks via |
571 |
> |
* power-of-two masking. |
572 |
> |
* |
573 |
> |
* In addition to basic queuing support, this class contains |
574 |
> |
* fields described elsewhere to control execution. It turns out |
575 |
> |
* to work better memory-layout-wise to include them in this |
576 |
> |
* class rather than a separate class. |
577 |
> |
* |
578 |
> |
* Performance on most platforms is very sensitive to placement of |
579 |
> |
* instances of both WorkQueues and their arrays -- we absolutely |
580 |
> |
* do not want multiple WorkQueue instances or multiple queue |
581 |
> |
* arrays sharing cache lines. (It would be best for queue objects |
582 |
> |
* and their arrays to share, but there is nothing available to |
583 |
> |
* help arrange that). Unfortunately, because they are recorded |
584 |
> |
* in a common array, WorkQueue instances are often moved to be |
585 |
> |
* adjacent by garbage collectors. To reduce impact, we use field |
586 |
> |
* padding that works OK on common platforms; this effectively |
587 |
> |
* trades off slightly slower average field access for the sake of |
588 |
> |
* avoiding really bad worst-case access. (Until better JVM |
589 |
> |
* support is in place, this padding is dependent on transient |
590 |
> |
* properties of JVM field layout rules.) We also take care in |
591 |
> |
* allocating, sizing and resizing the array. Non-shared queue |
592 |
> |
* arrays are initialized (via method growArray) by workers before |
593 |
> |
* use. Others are allocated on first use. |
594 |
|
*/ |
595 |
< |
public static final ForkJoinWorkerThreadFactory |
596 |
< |
defaultForkJoinWorkerThreadFactory = |
597 |
< |
new DefaultForkJoinWorkerThreadFactory(); |
595 |
> |
static final class WorkQueue { |
596 |
> |
/** |
597 |
> |
* Capacity of work-stealing queue array upon initialization. |
598 |
> |
* Must be a power of two; at least 4, but should be larger to |
599 |
> |
* reduce or eliminate cacheline sharing among queues. |
600 |
> |
* Currently, it is much larger, as a partial workaround for |
601 |
> |
* the fact that JVMs often place arrays in locations that |
602 |
> |
* share GC bookkeeping (especially cardmarks) such that |
603 |
> |
* per-write accesses encounter serious memory contention. |
604 |
> |
*/ |
605 |
> |
static final int INITIAL_QUEUE_CAPACITY = 1 << 13; |
606 |
|
|
607 |
< |
/** |
608 |
< |
* Permission required for callers of methods that may start or |
609 |
< |
* kill threads. |
610 |
< |
*/ |
611 |
< |
private static final RuntimePermission modifyThreadPermission = |
612 |
< |
new RuntimePermission("modifyThread"); |
607 |
> |
/** |
608 |
> |
* Maximum size for queue arrays. Must be a power of two less |
609 |
> |
* than or equal to 1 << (31 - width of array entry) to ensure |
610 |
> |
* lack of wraparound of index calculations, but defined to a |
611 |
> |
* value a bit less than this to help users trap runaway |
612 |
> |
* programs before saturating systems. |
613 |
> |
*/ |
614 |
> |
static final int MAXIMUM_QUEUE_CAPACITY = 1 << 26; // 64M |
615 |
|
|
616 |
< |
/** |
617 |
< |
* If there is a security manager, makes sure caller has |
618 |
< |
* permission to modify threads. |
619 |
< |
*/ |
620 |
< |
private static void checkPermission() { |
621 |
< |
SecurityManager security = System.getSecurityManager(); |
622 |
< |
if (security != null) |
623 |
< |
security.checkPermission(modifyThreadPermission); |
624 |
< |
} |
616 |
> |
volatile long totalSteals; // cumulative number of steals |
617 |
> |
int seed; // for random scanning; initialize nonzero |
618 |
> |
volatile int eventCount; // encoded inactivation count; < 0 if inactive |
619 |
> |
int nextWait; // encoded record of next event waiter |
620 |
> |
int rescans; // remaining scans until block |
621 |
> |
int nsteals; // top-level task executions since last idle |
622 |
> |
final int mode; // lifo, fifo, or shared |
623 |
> |
int poolIndex; // index of this queue in pool (or 0) |
624 |
> |
int stealHint; // index of most recent known stealer |
625 |
> |
volatile int runState; // 1: locked, -1: terminate; else 0 |
626 |
> |
volatile int base; // index of next slot for poll |
627 |
> |
int top; // index of next slot for push |
628 |
> |
ForkJoinTask<?>[] array; // the elements (initially unallocated) |
629 |
> |
final ForkJoinPool pool; // the containing pool (may be null) |
630 |
> |
final ForkJoinWorkerThread owner; // owning thread or null if shared |
631 |
> |
volatile Thread parker; // == owner during call to park; else null |
632 |
> |
ForkJoinTask<?> currentJoin; // task being joined in awaitJoin |
633 |
> |
ForkJoinTask<?> currentSteal; // current non-local task being executed |
634 |
> |
// Heuristic padding to ameliorate unfortunate memory placements |
635 |
> |
Object p00, p01, p02, p03, p04, p05, p06, p07; |
636 |
> |
Object p08, p09, p0a, p0b, p0c, p0d, p0e; |
637 |
> |
|
638 |
> |
WorkQueue(ForkJoinPool pool, ForkJoinWorkerThread owner, int mode) { |
639 |
> |
this.mode = mode; |
640 |
> |
this.pool = pool; |
641 |
> |
this.owner = owner; |
642 |
> |
// Place indices in the center of array (that is not yet allocated) |
643 |
> |
base = top = INITIAL_QUEUE_CAPACITY >>> 1; |
644 |
> |
} |
645 |
|
|
646 |
< |
/** |
647 |
< |
* Generator for assigning sequence numbers as pool names. |
648 |
< |
*/ |
649 |
< |
private static final AtomicInteger poolNumberGenerator = |
650 |
< |
new AtomicInteger(); |
646 |
> |
/** |
647 |
> |
* Returns the approximate number of tasks in the queue. |
648 |
> |
*/ |
649 |
> |
final int queueSize() { |
650 |
> |
int n = base - top; // non-owner callers must read base first |
651 |
> |
return (n >= 0) ? 0 : -n; // ignore transient negative |
652 |
> |
} |
653 |
|
|
654 |
< |
/** |
655 |
< |
* Absolute bound for parallelism level. Twice this number must |
656 |
< |
* fit into a 16bit field to enable word-packing for some counts. |
657 |
< |
*/ |
658 |
< |
private static final int MAX_THREADS = 0x7fff; |
654 |
> |
/** |
655 |
> |
* Provides a more accurate estimate of whether this queue has |
656 |
> |
* any tasks than does queueSize, by checking whether a |
657 |
> |
* near-empty queue has at least one unclaimed task. |
658 |
> |
*/ |
659 |
> |
final boolean isEmpty() { |
660 |
> |
ForkJoinTask<?>[] a; int m, s; |
661 |
> |
int n = base - (s = top); |
662 |
> |
return (n >= 0 || |
663 |
> |
(n == -1 && |
664 |
> |
((a = array) == null || |
665 |
> |
(m = a.length - 1) < 0 || |
666 |
> |
U.getObjectVolatile |
667 |
> |
(a, ((m & (s - 1)) << ASHIFT) + ABASE) == null))); |
668 |
> |
} |
669 |
|
|
670 |
< |
/** |
671 |
< |
* Array holding all worker threads in the pool. Array size must |
672 |
< |
* be a power of two. Updates and replacements are protected by |
673 |
< |
* workerLock, but the array is always kept in a consistent enough |
674 |
< |
* state to be randomly accessed without locking by workers |
675 |
< |
* performing work-stealing, as well as other traversal-based |
676 |
< |
* methods in this class. All readers must tolerate that some |
677 |
< |
* array slots may be null. |
678 |
< |
*/ |
679 |
< |
volatile ForkJoinWorkerThread[] workers; |
670 |
> |
/** |
671 |
> |
* Pushes a task. Call only by owner in unshared queues. |
672 |
> |
* |
673 |
> |
* @param task the task. Caller must ensure non-null. |
674 |
> |
* @throw RejectedExecutionException if array cannot be resized |
675 |
> |
*/ |
676 |
> |
final void push(ForkJoinTask<?> task) { |
677 |
> |
ForkJoinTask<?>[] a; ForkJoinPool p; |
678 |
> |
int s = top, m, n; |
679 |
> |
if ((a = array) != null) { // ignore if queue removed |
680 |
> |
U.putOrderedObject |
681 |
> |
(a, (((m = a.length - 1) & s) << ASHIFT) + ABASE, task); |
682 |
> |
if ((n = (top = s + 1) - base) <= 2) { |
683 |
> |
if ((p = pool) != null) |
684 |
> |
p.signalWork(); |
685 |
> |
} |
686 |
> |
else if (n >= m) |
687 |
> |
growArray(true); |
688 |
> |
} |
689 |
> |
} |
690 |
|
|
691 |
< |
/** |
692 |
< |
* Queue for external submissions. |
693 |
< |
*/ |
694 |
< |
private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue; |
691 |
> |
/** |
692 |
> |
* Pushes a task if lock is free and array is either big |
693 |
> |
* enough or can be resized to be big enough. |
694 |
> |
* |
695 |
> |
* @param task the task. Caller must ensure non-null. |
696 |
> |
* @return true if submitted |
697 |
> |
*/ |
698 |
> |
final boolean trySharedPush(ForkJoinTask<?> task) { |
699 |
> |
boolean submitted = false; |
700 |
> |
if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) { |
701 |
> |
ForkJoinTask<?>[] a = array; |
702 |
> |
int s = top; |
703 |
> |
try { |
704 |
> |
if ((a != null && a.length > s + 1 - base) || |
705 |
> |
(a = growArray(false)) != null) { // must presize |
706 |
> |
int j = (((a.length - 1) & s) << ASHIFT) + ABASE; |
707 |
> |
U.putObject(a, (long)j, task); // don't need "ordered" |
708 |
> |
top = s + 1; |
709 |
> |
submitted = true; |
710 |
> |
} |
711 |
> |
} finally { |
712 |
> |
runState = 0; // unlock |
713 |
> |
} |
714 |
> |
} |
715 |
> |
return submitted; |
716 |
> |
} |
717 |
|
|
718 |
< |
/** |
719 |
< |
* Lock protecting updates to workers array. |
720 |
< |
*/ |
721 |
< |
private final ReentrantLock workerLock; |
718 |
> |
/** |
719 |
> |
* Takes next task, if one exists, in LIFO order. Call only |
720 |
> |
* by owner in unshared queues. (We do not have a shared |
721 |
> |
* version of this method because it is never needed.) |
722 |
> |
*/ |
723 |
> |
final ForkJoinTask<?> pop() { |
724 |
> |
ForkJoinTask<?> t; int m; |
725 |
> |
ForkJoinTask<?>[] a = array; |
726 |
> |
if (a != null && (m = a.length - 1) >= 0) { |
727 |
> |
for (int s; (s = top - 1) - base >= 0;) { |
728 |
> |
int j = ((m & s) << ASHIFT) + ABASE; |
729 |
> |
if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) == null) |
730 |
> |
break; |
731 |
> |
if (U.compareAndSwapObject(a, j, t, null)) { |
732 |
> |
top = s; |
733 |
> |
return t; |
734 |
> |
} |
735 |
> |
} |
736 |
> |
} |
737 |
> |
return null; |
738 |
> |
} |
739 |
|
|
740 |
< |
/** |
741 |
< |
* Latch released upon termination. |
742 |
< |
*/ |
743 |
< |
private final CountDownLatch terminationLatch; |
740 |
> |
/** |
741 |
> |
* Takes a task in FIFO order if b is base of queue and a task |
742 |
> |
* can be claimed without contention. Specialized versions |
743 |
> |
* appear in ForkJoinPool methods scan and tryHelpStealer. |
744 |
> |
*/ |
745 |
> |
final ForkJoinTask<?> pollAt(int b) { |
746 |
> |
ForkJoinTask<?> t; ForkJoinTask<?>[] a; |
747 |
> |
if ((a = array) != null) { |
748 |
> |
int j = (((a.length - 1) & b) << ASHIFT) + ABASE; |
749 |
> |
if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) != null && |
750 |
> |
base == b && |
751 |
> |
U.compareAndSwapObject(a, j, t, null)) { |
752 |
> |
base = b + 1; |
753 |
> |
return t; |
754 |
> |
} |
755 |
> |
} |
756 |
> |
return null; |
757 |
> |
} |
758 |
|
|
759 |
< |
/** |
760 |
< |
* Creation factory for worker threads. |
761 |
< |
*/ |
762 |
< |
private final ForkJoinWorkerThreadFactory factory; |
759 |
> |
/** |
760 |
> |
* Takes next task, if one exists, in FIFO order. |
761 |
> |
*/ |
762 |
> |
final ForkJoinTask<?> poll() { |
763 |
> |
ForkJoinTask<?>[] a; int b; ForkJoinTask<?> t; |
764 |
> |
while ((b = base) - top < 0 && (a = array) != null) { |
765 |
> |
int j = (((a.length - 1) & b) << ASHIFT) + ABASE; |
766 |
> |
t = (ForkJoinTask<?>)U.getObjectVolatile(a, j); |
767 |
> |
if (t != null) { |
768 |
> |
if (base == b && |
769 |
> |
U.compareAndSwapObject(a, j, t, null)) { |
770 |
> |
base = b + 1; |
771 |
> |
return t; |
772 |
> |
} |
773 |
> |
} |
774 |
> |
else if (base == b) { |
775 |
> |
if (b + 1 == top) |
776 |
> |
break; |
777 |
> |
Thread.yield(); // wait for lagging update |
778 |
> |
} |
779 |
> |
} |
780 |
> |
return null; |
781 |
> |
} |
782 |
|
|
783 |
< |
/** |
784 |
< |
* Sum of per-thread steal counts, updated only when threads are |
785 |
< |
* idle or terminating. |
786 |
< |
*/ |
787 |
< |
private volatile long stealCount; |
783 |
> |
/** |
784 |
> |
* Takes next task, if one exists, in order specified by mode. |
785 |
> |
*/ |
786 |
> |
final ForkJoinTask<?> nextLocalTask() { |
787 |
> |
return mode == 0 ? pop() : poll(); |
788 |
> |
} |
789 |
|
|
790 |
< |
/** |
791 |
< |
* Encoded record of top of treiber stack of threads waiting for |
792 |
< |
* events. The top 32 bits contain the count being waited for. The |
793 |
< |
* bottom word contains one plus the pool index of waiting worker |
794 |
< |
* thread. |
795 |
< |
*/ |
796 |
< |
private volatile long eventWaiters; |
790 |
> |
/** |
791 |
> |
* Returns next task, if one exists, in order specified by mode. |
792 |
> |
*/ |
793 |
> |
final ForkJoinTask<?> peek() { |
794 |
> |
ForkJoinTask<?>[] a = array; int m; |
795 |
> |
if (a == null || (m = a.length - 1) < 0) |
796 |
> |
return null; |
797 |
> |
int i = mode == 0 ? top - 1 : base; |
798 |
> |
int j = ((i & m) << ASHIFT) + ABASE; |
799 |
> |
return (ForkJoinTask<?>)U.getObjectVolatile(a, j); |
800 |
> |
} |
801 |
> |
|
802 |
> |
/** |
803 |
> |
* Pops the given task only if it is at the current top. |
804 |
> |
*/ |
805 |
> |
final boolean tryUnpush(ForkJoinTask<?> t) { |
806 |
> |
ForkJoinTask<?>[] a; int s; |
807 |
> |
if ((a = array) != null && (s = top) != base && |
808 |
> |
U.compareAndSwapObject |
809 |
> |
(a, (((a.length - 1) & --s) << ASHIFT) + ABASE, t, null)) { |
810 |
> |
top = s; |
811 |
> |
return true; |
812 |
> |
} |
813 |
> |
return false; |
814 |
> |
} |
815 |
|
|
816 |
< |
private static final int EVENT_COUNT_SHIFT = 32; |
817 |
< |
private static final long WAITER_INDEX_MASK = (1L << EVENT_COUNT_SHIFT)-1L; |
816 |
> |
/** |
817 |
> |
* Polls the given task only if it is at the current base. |
818 |
> |
*/ |
819 |
> |
final boolean pollFor(ForkJoinTask<?> task) { |
820 |
> |
ForkJoinTask<?>[] a; int b; |
821 |
> |
if ((b = base) - top < 0 && (a = array) != null) { |
822 |
> |
int j = (((a.length - 1) & b) << ASHIFT) + ABASE; |
823 |
> |
if (U.getObjectVolatile(a, j) == task && base == b && |
824 |
> |
U.compareAndSwapObject(a, j, task, null)) { |
825 |
> |
base = b + 1; |
826 |
> |
return true; |
827 |
> |
} |
828 |
> |
} |
829 |
> |
return false; |
830 |
> |
} |
831 |
|
|
832 |
< |
/** |
833 |
< |
* A counter for events that may wake up worker threads: |
834 |
< |
* - Submission of a new task to the pool |
835 |
< |
* - A worker pushing a task on an empty queue |
836 |
< |
* - termination and reconfiguration |
837 |
< |
*/ |
838 |
< |
private volatile int eventCount; |
832 |
> |
/** |
833 |
> |
* If present, removes from queue and executes the given task, or |
834 |
> |
* any other cancelled task. Returns (true) immediately on any CAS |
835 |
> |
* or consistency check failure so caller can retry. |
836 |
> |
* |
837 |
> |
* @return false if no progress can be made |
838 |
> |
*/ |
839 |
> |
final boolean tryRemoveAndExec(ForkJoinTask<?> task) { |
840 |
> |
boolean removed = false, empty = true, progress = true; |
841 |
> |
ForkJoinTask<?>[] a; int m, s, b, n; |
842 |
> |
if ((a = array) != null && (m = a.length - 1) >= 0 && |
843 |
> |
(n = (s = top) - (b = base)) > 0) { |
844 |
> |
for (ForkJoinTask<?> t;;) { // traverse from s to b |
845 |
> |
int j = ((--s & m) << ASHIFT) + ABASE; |
846 |
> |
t = (ForkJoinTask<?>)U.getObjectVolatile(a, j); |
847 |
> |
if (t == null) // inconsistent length |
848 |
> |
break; |
849 |
> |
else if (t == task) { |
850 |
> |
if (s + 1 == top) { // pop |
851 |
> |
if (!U.compareAndSwapObject(a, j, task, null)) |
852 |
> |
break; |
853 |
> |
top = s; |
854 |
> |
removed = true; |
855 |
> |
} |
856 |
> |
else if (base == b) // replace with proxy |
857 |
> |
removed = U.compareAndSwapObject(a, j, task, |
858 |
> |
new EmptyTask()); |
859 |
> |
break; |
860 |
> |
} |
861 |
> |
else if (t.status >= 0) |
862 |
> |
empty = false; |
863 |
> |
else if (s + 1 == top) { // pop and throw away |
864 |
> |
if (U.compareAndSwapObject(a, j, t, null)) |
865 |
> |
top = s; |
866 |
> |
break; |
867 |
> |
} |
868 |
> |
if (--n == 0) { |
869 |
> |
if (!empty && base == b) |
870 |
> |
progress = false; |
871 |
> |
break; |
872 |
> |
} |
873 |
> |
} |
874 |
> |
} |
875 |
> |
if (removed) |
876 |
> |
task.doExec(); |
877 |
> |
return progress; |
878 |
> |
} |
879 |
|
|
880 |
< |
/** |
881 |
< |
* Lifecycle control. The low word contains the number of workers |
882 |
< |
* that are (probably) executing tasks. This value is atomically |
883 |
< |
* incremented before a worker gets a task to run, and decremented |
884 |
< |
* when worker has no tasks and cannot find any. Bits 16-18 |
885 |
< |
* contain runLevel value. When all are zero, the pool is |
886 |
< |
* running. Level transitions are monotonic (running -> shutdown |
887 |
< |
* -> terminating -> terminated) so each transition adds a bit. |
888 |
< |
* These are bundled together to ensure consistent read for |
889 |
< |
* termination checks (i.e., that runLevel is at least SHUTDOWN |
890 |
< |
* and active threads is zero). |
891 |
< |
*/ |
892 |
< |
private volatile int runState; |
880 |
> |
/** |
881 |
> |
* Initializes or doubles the capacity of array. Call either |
882 |
> |
* by owner or with lock held -- it is OK for base, but not |
883 |
> |
* top, to move while resizings are in progress. |
884 |
> |
* |
885 |
> |
* @param rejectOnFailure if true, throw exception if capacity |
886 |
> |
* exceeded (relayed ultimately to user); else return null. |
887 |
> |
*/ |
888 |
> |
final ForkJoinTask<?>[] growArray(boolean rejectOnFailure) { |
889 |
> |
ForkJoinTask<?>[] oldA = array; |
890 |
> |
int size = oldA != null ? oldA.length << 1 : INITIAL_QUEUE_CAPACITY; |
891 |
> |
if (size <= MAXIMUM_QUEUE_CAPACITY) { |
892 |
> |
int oldMask, t, b; |
893 |
> |
ForkJoinTask<?>[] a = array = new ForkJoinTask<?>[size]; |
894 |
> |
if (oldA != null && (oldMask = oldA.length - 1) >= 0 && |
895 |
> |
(t = top) - (b = base) > 0) { |
896 |
> |
int mask = size - 1; |
897 |
> |
do { |
898 |
> |
ForkJoinTask<?> x; |
899 |
> |
int oldj = ((b & oldMask) << ASHIFT) + ABASE; |
900 |
> |
int j = ((b & mask) << ASHIFT) + ABASE; |
901 |
> |
x = (ForkJoinTask<?>)U.getObjectVolatile(oldA, oldj); |
902 |
> |
if (x != null && |
903 |
> |
U.compareAndSwapObject(oldA, oldj, x, null)) |
904 |
> |
U.putObjectVolatile(a, j, x); |
905 |
> |
} while (++b != t); |
906 |
> |
} |
907 |
> |
return a; |
908 |
> |
} |
909 |
> |
else if (!rejectOnFailure) |
910 |
> |
return null; |
911 |
> |
else |
912 |
> |
throw new RejectedExecutionException("Queue capacity exceeded"); |
913 |
> |
} |
914 |
|
|
915 |
< |
// Note: The order among run level values matters. |
916 |
< |
private static final int RUNLEVEL_SHIFT = 16; |
917 |
< |
private static final int SHUTDOWN = 1 << RUNLEVEL_SHIFT; |
918 |
< |
private static final int TERMINATING = 1 << (RUNLEVEL_SHIFT + 1); |
919 |
< |
private static final int TERMINATED = 1 << (RUNLEVEL_SHIFT + 2); |
920 |
< |
private static final int ACTIVE_COUNT_MASK = (1 << RUNLEVEL_SHIFT) - 1; |
921 |
< |
private static final int ONE_ACTIVE = 1; // active update delta |
915 |
> |
/** |
916 |
> |
* Removes and cancels all known tasks, ignoring any exceptions. |
917 |
> |
*/ |
918 |
> |
final void cancelAll() { |
919 |
> |
ForkJoinTask.cancelIgnoringExceptions(currentJoin); |
920 |
> |
ForkJoinTask.cancelIgnoringExceptions(currentSteal); |
921 |
> |
for (ForkJoinTask<?> t; (t = poll()) != null; ) |
922 |
> |
ForkJoinTask.cancelIgnoringExceptions(t); |
923 |
> |
} |
924 |
|
|
925 |
< |
/** |
926 |
< |
* Holds number of total (i.e., created and not yet terminated) |
927 |
< |
* and running (i.e., not blocked on joins or other managed sync) |
928 |
< |
* threads, packed together to ensure consistent snapshot when |
929 |
< |
* making decisions about creating and suspending spare |
930 |
< |
* threads. Updated only by CAS. Note that adding a new worker |
931 |
< |
* requires incrementing both counts, since workers start off in |
932 |
< |
* running state. This field is also used for memory-fencing |
933 |
< |
* configuration parameters. |
934 |
< |
*/ |
935 |
< |
private volatile int workerCounts; |
925 |
> |
/** |
926 |
> |
* Computes next value for random probes. Scans don't require |
927 |
> |
* a very high quality generator, but also not a crummy one. |
928 |
> |
* Marsaglia xor-shift is cheap and works well enough. Note: |
929 |
> |
* This is manually inlined in its usages in ForkJoinPool to |
930 |
> |
* avoid writes inside busy scan loops. |
931 |
> |
*/ |
932 |
> |
final int nextSeed() { |
933 |
> |
int r = seed; |
934 |
> |
r ^= r << 13; |
935 |
> |
r ^= r >>> 17; |
936 |
> |
return seed = r ^= r << 5; |
937 |
> |
} |
938 |
|
|
939 |
< |
private static final int TOTAL_COUNT_SHIFT = 16; |
483 |
< |
private static final int RUNNING_COUNT_MASK = (1 << TOTAL_COUNT_SHIFT) - 1; |
484 |
< |
private static final int ONE_RUNNING = 1; |
485 |
< |
private static final int ONE_TOTAL = 1 << TOTAL_COUNT_SHIFT; |
939 |
> |
// Execution methods |
940 |
|
|
941 |
< |
/* |
942 |
< |
* Fields parallelism. maxPoolSize, locallyFifo, |
943 |
< |
* maintainsParallelism, and ueh are non-volatile, but external |
944 |
< |
* reads/writes use workerCount fences to ensure visability. |
945 |
< |
*/ |
941 |
> |
/** |
942 |
> |
* Removes and runs tasks until empty, using local mode |
943 |
> |
* ordering. Normally called only after checking for apparent |
944 |
> |
* non-emptiness. |
945 |
> |
*/ |
946 |
> |
final void runLocalTasks() { |
947 |
> |
// hoist checks from repeated pop/poll |
948 |
> |
ForkJoinTask<?>[] a; int m; |
949 |
> |
if ((a = array) != null && (m = a.length - 1) >= 0) { |
950 |
> |
if (mode == 0) { |
951 |
> |
for (int s; (s = top - 1) - base >= 0;) { |
952 |
> |
int j = ((m & s) << ASHIFT) + ABASE; |
953 |
> |
ForkJoinTask<?> t = |
954 |
> |
(ForkJoinTask<?>)U.getObjectVolatile(a, j); |
955 |
> |
if (t != null) { |
956 |
> |
if (U.compareAndSwapObject(a, j, t, null)) { |
957 |
> |
top = s; |
958 |
> |
t.doExec(); |
959 |
> |
} |
960 |
> |
} |
961 |
> |
else |
962 |
> |
break; |
963 |
> |
} |
964 |
> |
} |
965 |
> |
else { |
966 |
> |
for (int b; (b = base) - top < 0;) { |
967 |
> |
int j = ((m & b) << ASHIFT) + ABASE; |
968 |
> |
ForkJoinTask<?> t = |
969 |
> |
(ForkJoinTask<?>)U.getObjectVolatile(a, j); |
970 |
> |
if (t != null) { |
971 |
> |
if (base == b && |
972 |
> |
U.compareAndSwapObject(a, j, t, null)) { |
973 |
> |
base = b + 1; |
974 |
> |
t.doExec(); |
975 |
> |
} |
976 |
> |
} else if (base == b) { |
977 |
> |
if (b + 1 == top) |
978 |
> |
break; |
979 |
> |
Thread.yield(); // wait for lagging update |
980 |
> |
} |
981 |
> |
} |
982 |
> |
} |
983 |
> |
} |
984 |
> |
} |
985 |
> |
|
986 |
> |
/** |
987 |
> |
* Executes a top-level task and any local tasks remaining |
988 |
> |
* after execution. |
989 |
> |
* |
990 |
> |
* @return true unless terminating |
991 |
> |
*/ |
992 |
> |
final boolean runTask(ForkJoinTask<?> t) { |
993 |
> |
boolean alive = true; |
994 |
> |
if (t != null) { |
995 |
> |
currentSteal = t; |
996 |
> |
t.doExec(); |
997 |
> |
if (top != base) // conservative guard |
998 |
> |
runLocalTasks(); |
999 |
> |
++nsteals; |
1000 |
> |
currentSteal = null; |
1001 |
> |
} |
1002 |
> |
else if (runState < 0) // terminating |
1003 |
> |
alive = false; |
1004 |
> |
return alive; |
1005 |
> |
} |
1006 |
> |
|
1007 |
> |
/** |
1008 |
> |
* Executes a non-top-level (stolen) task. |
1009 |
> |
*/ |
1010 |
> |
final void runSubtask(ForkJoinTask<?> t) { |
1011 |
> |
if (t != null) { |
1012 |
> |
ForkJoinTask<?> ps = currentSteal; |
1013 |
> |
currentSteal = t; |
1014 |
> |
t.doExec(); |
1015 |
> |
currentSteal = ps; |
1016 |
> |
} |
1017 |
> |
} |
1018 |
> |
|
1019 |
> |
/** |
1020 |
> |
* Returns true if owned and not known to be blocked. |
1021 |
> |
*/ |
1022 |
> |
final boolean isApparentlyUnblocked() { |
1023 |
> |
Thread wt; Thread.State s; |
1024 |
> |
return (eventCount >= 0 && |
1025 |
> |
(wt = owner) != null && |
1026 |
> |
(s = wt.getState()) != Thread.State.BLOCKED && |
1027 |
> |
s != Thread.State.WAITING && |
1028 |
> |
s != Thread.State.TIMED_WAITING); |
1029 |
> |
} |
1030 |
> |
|
1031 |
> |
/** |
1032 |
> |
* If this owned and is not already interrupted, try to |
1033 |
> |
* interrupt and/or unpark, ignoring exceptions. |
1034 |
> |
*/ |
1035 |
> |
final void interruptOwner() { |
1036 |
> |
Thread wt, p; |
1037 |
> |
if ((wt = owner) != null && !wt.isInterrupted()) { |
1038 |
> |
try { |
1039 |
> |
wt.interrupt(); |
1040 |
> |
} catch (SecurityException ignore) { |
1041 |
> |
} |
1042 |
> |
} |
1043 |
> |
if ((p = parker) != null) |
1044 |
> |
U.unpark(p); |
1045 |
> |
} |
1046 |
> |
|
1047 |
> |
// Unsafe mechanics |
1048 |
> |
private static final sun.misc.Unsafe U; |
1049 |
> |
private static final long RUNSTATE; |
1050 |
> |
private static final int ABASE; |
1051 |
> |
private static final int ASHIFT; |
1052 |
> |
static { |
1053 |
> |
int s; |
1054 |
> |
try { |
1055 |
> |
U = getUnsafe(); |
1056 |
> |
Class<?> k = WorkQueue.class; |
1057 |
> |
Class<?> ak = ForkJoinTask[].class; |
1058 |
> |
RUNSTATE = U.objectFieldOffset |
1059 |
> |
(k.getDeclaredField("runState")); |
1060 |
> |
ABASE = U.arrayBaseOffset(ak); |
1061 |
> |
s = U.arrayIndexScale(ak); |
1062 |
> |
} catch (Exception e) { |
1063 |
> |
throw new Error(e); |
1064 |
> |
} |
1065 |
> |
if ((s & (s-1)) != 0) |
1066 |
> |
throw new Error("data type scale not a power of two"); |
1067 |
> |
ASHIFT = 31 - Integer.numberOfLeadingZeros(s); |
1068 |
> |
} |
1069 |
> |
} |
1070 |
|
|
1071 |
|
/** |
1072 |
< |
* The target parallelism level. |
1072 |
> |
* Per-thread records for threads that submit to pools. Currently |
1073 |
> |
* holds only pseudo-random seed / index that is used to choose |
1074 |
> |
* submission queues in method doSubmit. In the future, this may |
1075 |
> |
* also incorporate a means to implement different task rejection |
1076 |
> |
* and resubmission policies. |
1077 |
> |
* |
1078 |
> |
* Seeds for submitters and workers/workQueues work in basically |
1079 |
> |
* the same way but are initialized and updated using slightly |
1080 |
> |
* different mechanics. Both are initialized using the same |
1081 |
> |
* approach as in class ThreadLocal, where successive values are |
1082 |
> |
* unlikely to collide with previous values. This is done during |
1083 |
> |
* registration for workers, but requires a separate AtomicInteger |
1084 |
> |
* for submitters. Seeds are then randomly modified upon |
1085 |
> |
* collisions using xorshifts, which requires a non-zero seed. |
1086 |
|
*/ |
1087 |
< |
private int parallelism; |
1087 |
> |
static final class Submitter { |
1088 |
> |
int seed; |
1089 |
> |
Submitter() { |
1090 |
> |
int s = nextSubmitterSeed.getAndAdd(SEED_INCREMENT); |
1091 |
> |
seed = (s == 0) ? 1 : s; // ensure non-zero |
1092 |
> |
} |
1093 |
> |
} |
1094 |
> |
|
1095 |
> |
/** ThreadLocal class for Submitters */ |
1096 |
> |
static final class ThreadSubmitter extends ThreadLocal<Submitter> { |
1097 |
> |
public Submitter initialValue() { return new Submitter(); } |
1098 |
> |
} |
1099 |
> |
|
1100 |
> |
// static fields (initialized in static initializer below) |
1101 |
|
|
1102 |
|
/** |
1103 |
< |
* The maximum allowed pool size. |
1103 |
> |
* Creates a new ForkJoinWorkerThread. This factory is used unless |
1104 |
> |
* overridden in ForkJoinPool constructors. |
1105 |
|
*/ |
1106 |
< |
private int maxPoolSize; |
1106 |
> |
public static final ForkJoinWorkerThreadFactory |
1107 |
> |
defaultForkJoinWorkerThreadFactory; |
1108 |
|
|
1109 |
|
/** |
1110 |
< |
* True if use local fifo, not default lifo, for local polling |
505 |
< |
* Replicated by ForkJoinWorkerThreads |
1110 |
> |
* Generator for assigning sequence numbers as pool names. |
1111 |
|
*/ |
1112 |
< |
private boolean locallyFifo; |
1112 |
> |
private static final AtomicInteger poolNumberGenerator; |
1113 |
|
|
1114 |
|
/** |
1115 |
< |
* Controls whether to add spares to maintain parallelism |
1115 |
> |
* Generator for initial hashes/seeds for submitters. Accessed by |
1116 |
> |
* Submitter class constructor. |
1117 |
|
*/ |
1118 |
< |
private boolean maintainsParallelism; |
1118 |
> |
static final AtomicInteger nextSubmitterSeed; |
1119 |
|
|
1120 |
|
/** |
1121 |
< |
* The uncaught exception handler used when any worker |
1122 |
< |
* abruptly terminates |
1121 |
> |
* Permission required for callers of methods that may start or |
1122 |
> |
* kill threads. |
1123 |
|
*/ |
1124 |
< |
private Thread.UncaughtExceptionHandler ueh; |
1124 |
> |
private static final RuntimePermission modifyThreadPermission; |
1125 |
|
|
1126 |
|
/** |
1127 |
< |
* Pool number, just for assigning useful names to worker threads |
1127 |
> |
* Per-thread submission bookeeping. Shared across all pools |
1128 |
> |
* to reduce ThreadLocal pollution and because random motion |
1129 |
> |
* to avoid contention in one pool is likely to hold for others. |
1130 |
|
*/ |
1131 |
< |
private final int poolNumber; |
1131 |
> |
private static final ThreadSubmitter submitters; |
1132 |
|
|
1133 |
< |
// utilities for updating fields |
1133 |
> |
// static constants |
1134 |
|
|
1135 |
|
/** |
1136 |
< |
* Adds delta to running count. Used mainly by ForkJoinTask. |
1137 |
< |
* |
1138 |
< |
* @param delta the number to add |
1136 |
> |
* The wakeup interval (in nanoseconds) for a worker waiting for a |
1137 |
> |
* task when the pool is quiescent to instead try to shrink the |
1138 |
> |
* number of workers. The exact value does not matter too |
1139 |
> |
* much. It must be short enough to release resources during |
1140 |
> |
* sustained periods of idleness, but not so short that threads |
1141 |
> |
* are continually re-created. |
1142 |
|
*/ |
1143 |
< |
final void updateRunningCount(int delta) { |
1144 |
< |
int wc; |
534 |
< |
do {} while (!UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
535 |
< |
wc = workerCounts, |
536 |
< |
wc + delta)); |
537 |
< |
} |
1143 |
> |
private static final long SHRINK_RATE = |
1144 |
> |
4L * 1000L * 1000L * 1000L; // 4 seconds |
1145 |
|
|
1146 |
|
/** |
1147 |
< |
* Write fence for user modifications of pool parameters |
1148 |
< |
* (parallelism. etc). Note that it doesn't matter if CAS fails. |
1147 |
> |
* The timeout value for attempted shrinkage, includes |
1148 |
> |
* some slop to cope with system timer imprecision. |
1149 |
|
*/ |
1150 |
< |
private void workerCountWriteFence() { |
544 |
< |
int wc; |
545 |
< |
UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
546 |
< |
wc = workerCounts, wc); |
547 |
< |
} |
1150 |
> |
private static final long SHRINK_TIMEOUT = SHRINK_RATE - (SHRINK_RATE / 10); |
1151 |
|
|
1152 |
|
/** |
1153 |
< |
* Read fence for external reads of pool parameters |
1154 |
< |
* (parallelism. maxPoolSize, etc). |
1153 |
> |
* The maximum stolen->joining link depth allowed in method |
1154 |
> |
* tryHelpStealer. Must be a power of two. This value also |
1155 |
> |
* controls the maximum number of times to try to help join a task |
1156 |
> |
* without any apparent progress or change in pool state before |
1157 |
> |
* giving up and blocking (see awaitJoin). Depths for legitimate |
1158 |
> |
* chains are unbounded, but we use a fixed constant to avoid |
1159 |
> |
* (otherwise unchecked) cycles and to bound staleness of |
1160 |
> |
* traversal parameters at the expense of sometimes blocking when |
1161 |
> |
* we could be helping. |
1162 |
|
*/ |
1163 |
< |
private void workerCountReadFence() { |
554 |
< |
int ignore = workerCounts; |
555 |
< |
} |
1163 |
> |
private static final int MAX_HELP = 32; |
1164 |
|
|
1165 |
|
/** |
1166 |
< |
* Tries incrementing active count; fails on contention. |
1167 |
< |
* Called by workers before executing tasks. |
1168 |
< |
* |
1169 |
< |
* @return true on success |
1166 |
> |
* Secondary time-based bound (in nanosecs) for helping attempts |
1167 |
> |
* before trying compensated blocking in awaitJoin. Used in |
1168 |
> |
* conjunction with MAX_HELP to reduce variance due to different |
1169 |
> |
* polling rates associated with different helping options. The |
1170 |
> |
* value should roughly approximate the time required to create |
1171 |
> |
* and/or activate a worker thread. |
1172 |
|
*/ |
1173 |
< |
final boolean tryIncrementActiveCount() { |
564 |
< |
int c; |
565 |
< |
return UNSAFE.compareAndSwapInt(this, runStateOffset, |
566 |
< |
c = runState, c + ONE_ACTIVE); |
567 |
< |
} |
1173 |
> |
private static final long COMPENSATION_DELAY = 100L * 1000L; // 0.1 millisec |
1174 |
|
|
1175 |
|
/** |
1176 |
< |
* Tries decrementing active count; fails on contention. |
1177 |
< |
* Called when workers cannot find tasks to run. |
1176 |
> |
* Increment for seed generators. See class ThreadLocal for |
1177 |
> |
* explanation. |
1178 |
|
*/ |
1179 |
< |
final boolean tryDecrementActiveCount() { |
574 |
< |
int c; |
575 |
< |
return UNSAFE.compareAndSwapInt(this, runStateOffset, |
576 |
< |
c = runState, c - ONE_ACTIVE); |
577 |
< |
} |
1179 |
> |
private static final int SEED_INCREMENT = 0x61c88647; |
1180 |
|
|
1181 |
|
/** |
1182 |
< |
* Advances to at least the given level. Returns true if not |
1183 |
< |
* already in at least the given level. |
1182 |
> |
* Bits and masks for control variables |
1183 |
> |
* |
1184 |
> |
* Field ctl is a long packed with: |
1185 |
> |
* AC: Number of active running workers minus target parallelism (16 bits) |
1186 |
> |
* TC: Number of total workers minus target parallelism (16 bits) |
1187 |
> |
* ST: true if pool is terminating (1 bit) |
1188 |
> |
* EC: the wait count of top waiting thread (15 bits) |
1189 |
> |
* ID: poolIndex of top of Treiber stack of waiters (16 bits) |
1190 |
> |
* |
1191 |
> |
* When convenient, we can extract the upper 32 bits of counts and |
1192 |
> |
* the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e = |
1193 |
> |
* (int)ctl. The ec field is never accessed alone, but always |
1194 |
> |
* together with id and st. The offsets of counts by the target |
1195 |
> |
* parallelism and the positionings of fields makes it possible to |
1196 |
> |
* perform the most common checks via sign tests of fields: When |
1197 |
> |
* ac is negative, there are not enough active workers, when tc is |
1198 |
> |
* negative, there are not enough total workers, and when e is |
1199 |
> |
* negative, the pool is terminating. To deal with these possibly |
1200 |
> |
* negative fields, we use casts in and out of "short" and/or |
1201 |
> |
* signed shifts to maintain signedness. |
1202 |
> |
* |
1203 |
> |
* When a thread is queued (inactivated), its eventCount field is |
1204 |
> |
* set negative, which is the only way to tell if a worker is |
1205 |
> |
* prevented from executing tasks, even though it must continue to |
1206 |
> |
* scan for them to avoid queuing races. Note however that |
1207 |
> |
* eventCount updates lag releases so usage requires care. |
1208 |
> |
* |
1209 |
> |
* Field runState is an int packed with: |
1210 |
> |
* SHUTDOWN: true if shutdown is enabled (1 bit) |
1211 |
> |
* SEQ: a sequence number updated upon (de)registering workers (30 bits) |
1212 |
> |
* INIT: set true after workQueues array construction (1 bit) |
1213 |
> |
* |
1214 |
> |
* The sequence number enables simple consistency checks: |
1215 |
> |
* Staleness of read-only operations on the workQueues array can |
1216 |
> |
* be checked by comparing runState before vs after the reads. |
1217 |
|
*/ |
583 |
– |
private boolean advanceRunLevel(int level) { |
584 |
– |
for (;;) { |
585 |
– |
int s = runState; |
586 |
– |
if ((s & level) != 0) |
587 |
– |
return false; |
588 |
– |
if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, s | level)) |
589 |
– |
return true; |
590 |
– |
} |
591 |
– |
} |
1218 |
|
|
1219 |
< |
// workers array maintenance |
1219 |
> |
// bit positions/shifts for fields |
1220 |
> |
private static final int AC_SHIFT = 48; |
1221 |
> |
private static final int TC_SHIFT = 32; |
1222 |
> |
private static final int ST_SHIFT = 31; |
1223 |
> |
private static final int EC_SHIFT = 16; |
1224 |
|
|
1225 |
< |
/** |
1226 |
< |
* Records and returns a workers array index for new worker. |
1227 |
< |
*/ |
1228 |
< |
private int recordWorker(ForkJoinWorkerThread w) { |
1229 |
< |
// Try using slot totalCount-1. If not available, scan and/or resize |
1230 |
< |
int k = (workerCounts >>> TOTAL_COUNT_SHIFT) - 1; |
601 |
< |
final ReentrantLock lock = this.workerLock; |
602 |
< |
lock.lock(); |
603 |
< |
try { |
604 |
< |
ForkJoinWorkerThread[] ws = workers; |
605 |
< |
int len = ws.length; |
606 |
< |
if (k < 0 || k >= len || ws[k] != null) { |
607 |
< |
for (k = 0; k < len && ws[k] != null; ++k) |
608 |
< |
; |
609 |
< |
if (k == len) |
610 |
< |
ws = Arrays.copyOf(ws, len << 1); |
611 |
< |
} |
612 |
< |
ws[k] = w; |
613 |
< |
workers = ws; // volatile array write ensures slot visibility |
614 |
< |
} finally { |
615 |
< |
lock.unlock(); |
616 |
< |
} |
617 |
< |
return k; |
618 |
< |
} |
1225 |
> |
// bounds |
1226 |
> |
private static final int SMASK = 0xffff; // short bits |
1227 |
> |
private static final int MAX_CAP = 0x7fff; // max #workers - 1 |
1228 |
> |
private static final int SQMASK = 0xfffe; // even short bits |
1229 |
> |
private static final int SHORT_SIGN = 1 << 15; |
1230 |
> |
private static final int INT_SIGN = 1 << 31; |
1231 |
|
|
1232 |
< |
/** |
1233 |
< |
* Nulls out record of worker in workers array |
1234 |
< |
*/ |
1235 |
< |
private void forgetWorker(ForkJoinWorkerThread w) { |
624 |
< |
int idx = w.poolIndex; |
625 |
< |
// Locking helps method recordWorker avoid unecessary expansion |
626 |
< |
final ReentrantLock lock = this.workerLock; |
627 |
< |
lock.lock(); |
628 |
< |
try { |
629 |
< |
ForkJoinWorkerThread[] ws = workers; |
630 |
< |
if (idx >= 0 && idx < ws.length && ws[idx] == w) // verify |
631 |
< |
ws[idx] = null; |
632 |
< |
} finally { |
633 |
< |
lock.unlock(); |
634 |
< |
} |
635 |
< |
} |
1232 |
> |
// masks |
1233 |
> |
private static final long STOP_BIT = 0x0001L << ST_SHIFT; |
1234 |
> |
private static final long AC_MASK = ((long)SMASK) << AC_SHIFT; |
1235 |
> |
private static final long TC_MASK = ((long)SMASK) << TC_SHIFT; |
1236 |
|
|
1237 |
< |
// adding and removing workers |
1237 |
> |
// units for incrementing and decrementing |
1238 |
> |
private static final long TC_UNIT = 1L << TC_SHIFT; |
1239 |
> |
private static final long AC_UNIT = 1L << AC_SHIFT; |
1240 |
|
|
1241 |
< |
/** |
1242 |
< |
* Tries to create and add new worker. Assumes that worker counts |
1243 |
< |
* are already updated to accommodate the worker, so adjusts on |
1244 |
< |
* failure. |
1245 |
< |
* |
1246 |
< |
* @return new worker or null if creation failed |
1247 |
< |
*/ |
1248 |
< |
private ForkJoinWorkerThread addWorker() { |
1249 |
< |
ForkJoinWorkerThread w = null; |
1241 |
> |
// masks and units for dealing with u = (int)(ctl >>> 32) |
1242 |
> |
private static final int UAC_SHIFT = AC_SHIFT - 32; |
1243 |
> |
private static final int UTC_SHIFT = TC_SHIFT - 32; |
1244 |
> |
private static final int UAC_MASK = SMASK << UAC_SHIFT; |
1245 |
> |
private static final int UTC_MASK = SMASK << UTC_SHIFT; |
1246 |
> |
private static final int UAC_UNIT = 1 << UAC_SHIFT; |
1247 |
> |
private static final int UTC_UNIT = 1 << UTC_SHIFT; |
1248 |
> |
|
1249 |
> |
// masks and units for dealing with e = (int)ctl |
1250 |
> |
private static final int E_MASK = 0x7fffffff; // no STOP_BIT |
1251 |
> |
private static final int E_SEQ = 1 << EC_SHIFT; |
1252 |
> |
|
1253 |
> |
// runState bits |
1254 |
> |
private static final int SHUTDOWN = 1 << 31; |
1255 |
> |
|
1256 |
> |
// access mode for WorkQueue |
1257 |
> |
static final int LIFO_QUEUE = 0; |
1258 |
> |
static final int FIFO_QUEUE = 1; |
1259 |
> |
static final int SHARED_QUEUE = -1; |
1260 |
> |
|
1261 |
> |
// Instance fields |
1262 |
> |
|
1263 |
> |
/* |
1264 |
> |
* Field layout order in this class tends to matter more than one |
1265 |
> |
* would like. Runtime layout order is only loosely related to |
1266 |
> |
* declaration order and may differ across JVMs, but the following |
1267 |
> |
* empirically works OK on current JVMs. |
1268 |
> |
*/ |
1269 |
> |
|
1270 |
> |
volatile long ctl; // main pool control |
1271 |
> |
final int parallelism; // parallelism level |
1272 |
> |
final int localMode; // per-worker scheduling mode |
1273 |
> |
final int submitMask; // submit queue index bound |
1274 |
> |
int nextSeed; // for initializing worker seeds |
1275 |
> |
volatile int runState; // shutdown status and seq |
1276 |
> |
WorkQueue[] workQueues; // main registry |
1277 |
> |
final Mutex lock; // for registration |
1278 |
> |
final Condition termination; // for awaitTermination |
1279 |
> |
final ForkJoinWorkerThreadFactory factory; // factory for new workers |
1280 |
> |
final Thread.UncaughtExceptionHandler ueh; // per-worker UEH |
1281 |
> |
final AtomicLong stealCount; // collect counts when terminated |
1282 |
> |
final AtomicInteger nextWorkerNumber; // to create worker name string |
1283 |
> |
final String workerNamePrefix; // to create worker name string |
1284 |
> |
|
1285 |
> |
// Creating, registering, and deregistering workers |
1286 |
> |
|
1287 |
> |
/** |
1288 |
> |
* Tries to create and start a worker |
1289 |
> |
*/ |
1290 |
> |
private void addWorker() { |
1291 |
> |
Throwable ex = null; |
1292 |
> |
ForkJoinWorkerThread wt = null; |
1293 |
|
try { |
1294 |
< |
w = factory.newThread(this); |
1295 |
< |
} finally { // Adjust on either null or exceptional factory return |
1296 |
< |
if (w == null) { |
652 |
< |
onWorkerCreationFailure(); |
653 |
< |
return null; |
1294 |
> |
if ((wt = factory.newThread(this)) != null) { |
1295 |
> |
wt.start(); |
1296 |
> |
return; |
1297 |
|
} |
1298 |
+ |
} catch (Throwable e) { |
1299 |
+ |
ex = e; |
1300 |
|
} |
1301 |
< |
w.start(recordWorker(w), locallyFifo, ueh); |
657 |
< |
return w; |
1301 |
> |
deregisterWorker(wt, ex); // adjust counts etc on failure |
1302 |
|
} |
1303 |
|
|
1304 |
|
/** |
1305 |
< |
* Adjusts counts upon failure to create worker |
1305 |
> |
* Callback from ForkJoinWorkerThread constructor to assign a |
1306 |
> |
* public name. This must be separate from registerWorker because |
1307 |
> |
* it is called during the "super" constructor call in |
1308 |
> |
* ForkJoinWorkerThread. |
1309 |
|
*/ |
1310 |
< |
private void onWorkerCreationFailure() { |
1311 |
< |
int c; |
1312 |
< |
do {} while (!UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
666 |
< |
c = workerCounts, |
667 |
< |
c - (ONE_RUNNING|ONE_TOTAL))); |
668 |
< |
tryTerminate(false); // in case of failure during shutdown |
1310 |
> |
final String nextWorkerName() { |
1311 |
> |
return workerNamePrefix.concat |
1312 |
> |
(Integer.toString(nextWorkerNumber.addAndGet(1))); |
1313 |
|
} |
1314 |
|
|
1315 |
|
/** |
1316 |
< |
* Create enough total workers to establish target parallelism, |
1317 |
< |
* giving up if terminating or addWorker fails |
1316 |
> |
* Callback from ForkJoinWorkerThread constructor to establish its |
1317 |
> |
* poolIndex and record its WorkQueue. To avoid scanning bias due |
1318 |
> |
* to packing entries in front of the workQueues array, we treat |
1319 |
> |
* the array as a simple power-of-two hash table using per-thread |
1320 |
> |
* seed as hash, expanding as needed. |
1321 |
> |
* |
1322 |
> |
* @param w the worker's queue |
1323 |
|
*/ |
1324 |
< |
private void ensureEnoughTotalWorkers() { |
1325 |
< |
int wc; |
1326 |
< |
while (runState < TERMINATING && |
1327 |
< |
((wc = workerCounts) >>> TOTAL_COUNT_SHIFT) < parallelism) { |
1328 |
< |
if ((UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
1329 |
< |
wc, wc + (ONE_RUNNING|ONE_TOTAL)) && |
1330 |
< |
addWorker() == null)) |
1331 |
< |
break; |
1324 |
> |
final void registerWorker(WorkQueue w) { |
1325 |
> |
Mutex lock = this.lock; |
1326 |
> |
lock.lock(); |
1327 |
> |
try { |
1328 |
> |
WorkQueue[] ws = workQueues; |
1329 |
> |
if (w != null && ws != null) { // skip on shutdown/failure |
1330 |
> |
int rs, n; |
1331 |
> |
while ((n = ws.length) < // ensure can hold total |
1332 |
> |
(parallelism + (short)(ctl >>> TC_SHIFT) << 1)) |
1333 |
> |
workQueues = ws = Arrays.copyOf(ws, n << 1); |
1334 |
> |
int m = n - 1; |
1335 |
> |
int s = nextSeed += SEED_INCREMENT; // rarely-colliding sequence |
1336 |
> |
w.seed = (s == 0) ? 1 : s; // ensure non-zero seed |
1337 |
> |
int r = (s << 1) | 1; // use odd-numbered indices |
1338 |
> |
while (ws[r &= m] != null) // step by approx half size |
1339 |
> |
r += ((n >>> 1) & SQMASK) + 2; |
1340 |
> |
w.eventCount = w.poolIndex = r; // establish before recording |
1341 |
> |
ws[r] = w; // also update seq |
1342 |
> |
runState = ((rs = runState) & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN); |
1343 |
> |
} |
1344 |
> |
} finally { |
1345 |
> |
lock.unlock(); |
1346 |
|
} |
1347 |
|
} |
1348 |
|
|
1349 |
|
/** |
1350 |
< |
* Final callback from terminating worker. Removes record of |
1350 |
> |
* Final callback from terminating worker, as well as upon failure |
1351 |
> |
* to construct or start a worker in addWorker. Removes record of |
1352 |
|
* worker from array, and adjusts counts. If pool is shutting |
1353 |
< |
* down, tries to complete terminatation, else possibly replaces |
690 |
< |
* the worker. |
1353 |
> |
* down, tries to complete termination. |
1354 |
|
* |
1355 |
< |
* @param w the worker |
1355 |
> |
* @param wt the worker thread or null if addWorker failed |
1356 |
> |
* @param ex the exception causing failure, or null if none |
1357 |
|
*/ |
1358 |
< |
final void workerTerminated(ForkJoinWorkerThread w) { |
1359 |
< |
if (w.active) { // force inactive |
1360 |
< |
w.active = false; |
1361 |
< |
do {} while (!tryDecrementActiveCount()); |
1358 |
> |
final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) { |
1359 |
> |
Mutex lock = this.lock; |
1360 |
> |
WorkQueue w = null; |
1361 |
> |
if (wt != null && (w = wt.workQueue) != null) { |
1362 |
> |
w.runState = -1; // ensure runState is set |
1363 |
> |
stealCount.getAndAdd(w.totalSteals + w.nsteals); |
1364 |
> |
int idx = w.poolIndex; |
1365 |
> |
lock.lock(); |
1366 |
> |
try { // remove record from array |
1367 |
> |
WorkQueue[] ws = workQueues; |
1368 |
> |
if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w) |
1369 |
> |
ws[idx] = null; |
1370 |
> |
} finally { |
1371 |
> |
lock.unlock(); |
1372 |
> |
} |
1373 |
> |
} |
1374 |
> |
|
1375 |
> |
long c; // adjust ctl counts |
1376 |
> |
do {} while (!U.compareAndSwapLong |
1377 |
> |
(this, CTL, c = ctl, (((c - AC_UNIT) & AC_MASK) | |
1378 |
> |
((c - TC_UNIT) & TC_MASK) | |
1379 |
> |
(c & ~(AC_MASK|TC_MASK))))); |
1380 |
> |
|
1381 |
> |
if (!tryTerminate(false, false) && w != null) { |
1382 |
> |
w.cancelAll(); // cancel remaining tasks |
1383 |
> |
if (w.array != null) // suppress signal if never ran |
1384 |
> |
signalWork(); // wake up or create replacement |
1385 |
> |
if (ex == null) // help clean refs on way out |
1386 |
> |
ForkJoinTask.helpExpungeStaleExceptions(); |
1387 |
> |
} |
1388 |
> |
|
1389 |
> |
if (ex != null) // rethrow |
1390 |
> |
U.throwException(ex); |
1391 |
> |
} |
1392 |
> |
|
1393 |
> |
|
1394 |
> |
// Submissions |
1395 |
> |
|
1396 |
> |
/** |
1397 |
> |
* Unless shutting down, adds the given task to a submission queue |
1398 |
> |
* at submitter's current queue index (modulo submission |
1399 |
> |
* range). If no queue exists at the index, one is created. If |
1400 |
> |
* the queue is busy, another index is randomly chosen. The |
1401 |
> |
* submitMask bounds the effective number of queues to the |
1402 |
> |
* (nearest power of two for) parallelism level. |
1403 |
> |
* |
1404 |
> |
* @param task the task. Caller must ensure non-null. |
1405 |
> |
*/ |
1406 |
> |
private void doSubmit(ForkJoinTask<?> task) { |
1407 |
> |
Submitter s = submitters.get(); |
1408 |
> |
for (int r = s.seed, m = submitMask;;) { |
1409 |
> |
WorkQueue[] ws; WorkQueue q; |
1410 |
> |
int k = r & m & SQMASK; // use only even indices |
1411 |
> |
if (runState < 0 || (ws = workQueues) == null || ws.length <= k) |
1412 |
> |
throw new RejectedExecutionException(); // shutting down |
1413 |
> |
else if ((q = ws[k]) == null) { // create new queue |
1414 |
> |
WorkQueue nq = new WorkQueue(this, null, SHARED_QUEUE); |
1415 |
> |
Mutex lock = this.lock; // construct outside lock |
1416 |
> |
lock.lock(); |
1417 |
> |
try { // recheck under lock |
1418 |
> |
int rs = runState; // to update seq |
1419 |
> |
if (ws == workQueues && ws[k] == null) { |
1420 |
> |
ws[k] = nq; |
1421 |
> |
runState = ((rs & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN)); |
1422 |
> |
} |
1423 |
> |
} finally { |
1424 |
> |
lock.unlock(); |
1425 |
> |
} |
1426 |
> |
} |
1427 |
> |
else if (q.trySharedPush(task)) { |
1428 |
> |
signalWork(); |
1429 |
> |
return; |
1430 |
> |
} |
1431 |
> |
else if (m > 1) { // move to a different index |
1432 |
> |
r ^= r << 13; // same xorshift as WorkQueues |
1433 |
> |
r ^= r >>> 17; |
1434 |
> |
s.seed = r ^= r << 5; |
1435 |
> |
} |
1436 |
> |
else |
1437 |
> |
Thread.yield(); // yield if no alternatives |
1438 |
|
} |
699 |
– |
forgetWorker(w); |
700 |
– |
|
701 |
– |
// decrement total count, and if was running, running count |
702 |
– |
int unit = w.isTrimmed()? ONE_TOTAL : (ONE_RUNNING|ONE_TOTAL); |
703 |
– |
int wc; |
704 |
– |
do {} while (!UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
705 |
– |
wc = workerCounts, wc - unit)); |
706 |
– |
|
707 |
– |
accumulateStealCount(w); // collect final count |
708 |
– |
if (!tryTerminate(false)) |
709 |
– |
ensureEnoughTotalWorkers(); |
1439 |
|
} |
1440 |
|
|
1441 |
< |
// Waiting for and signalling events |
1441 |
> |
// Maintaining ctl counts |
1442 |
|
|
1443 |
|
/** |
1444 |
< |
* Ensures eventCount on exit is different (mod 2^32) than on |
716 |
< |
* entry. CAS failures are OK -- any change in count suffices. |
1444 |
> |
* Increments active count; mainly called upon return from blocking. |
1445 |
|
*/ |
1446 |
< |
private void advanceEventCount() { |
1447 |
< |
int c; |
1448 |
< |
UNSAFE.compareAndSwapInt(this, eventCountOffset, c = eventCount, c+1); |
1446 |
> |
final void incrementActiveCount() { |
1447 |
> |
long c; |
1448 |
> |
do {} while (!U.compareAndSwapLong(this, CTL, c = ctl, c + AC_UNIT)); |
1449 |
|
} |
1450 |
|
|
1451 |
|
/** |
1452 |
< |
* Releases workers blocked on a count not equal to current count. |
725 |
< |
*/ |
726 |
< |
final void releaseWaiters() { |
727 |
< |
long top; |
728 |
< |
int id; |
729 |
< |
while ((id = (int)((top = eventWaiters) & WAITER_INDEX_MASK)) > 0 && |
730 |
< |
(int)(top >>> EVENT_COUNT_SHIFT) != eventCount) { |
731 |
< |
ForkJoinWorkerThread[] ws = workers; |
732 |
< |
ForkJoinWorkerThread w; |
733 |
< |
if (ws.length >= id && (w = ws[id - 1]) != null && |
734 |
< |
UNSAFE.compareAndSwapLong(this, eventWaitersOffset, |
735 |
< |
top, w.nextWaiter)) |
736 |
< |
LockSupport.unpark(w); |
737 |
< |
} |
738 |
< |
} |
739 |
< |
|
740 |
< |
/** |
741 |
< |
* Advances eventCount and releases waiters until interference by |
742 |
< |
* other releasing threads is detected. |
1452 |
> |
* Tries to activate or create a worker if too few are active. |
1453 |
|
*/ |
1454 |
|
final void signalWork() { |
1455 |
< |
int ec; |
1456 |
< |
UNSAFE.compareAndSwapInt(this, eventCountOffset, ec=eventCount, ec+1); |
1457 |
< |
outer:for (;;) { |
1458 |
< |
long top = eventWaiters; |
1459 |
< |
ec = eventCount; |
1460 |
< |
for (;;) { |
1461 |
< |
ForkJoinWorkerThread[] ws; ForkJoinWorkerThread w; |
1462 |
< |
int id = (int)(top & WAITER_INDEX_MASK); |
1463 |
< |
if (id <= 0 || (int)(top >>> EVENT_COUNT_SHIFT) == ec) |
1464 |
< |
return; |
1465 |
< |
if ((ws = workers).length < id || (w = ws[id - 1]) == null || |
1466 |
< |
!UNSAFE.compareAndSwapLong(this, eventWaitersOffset, |
1467 |
< |
top, top = w.nextWaiter)) |
1468 |
< |
continue outer; // possibly stale; reread |
1469 |
< |
LockSupport.unpark(w); |
1470 |
< |
if (top != eventWaiters) // let someone else take over |
1471 |
< |
return; |
1455 |
> |
long c; int u; |
1456 |
> |
while ((u = (int)((c = ctl) >>> 32)) < 0) { // too few active |
1457 |
> |
WorkQueue[] ws = workQueues; int e, i; WorkQueue w; Thread p; |
1458 |
> |
if ((e = (int)c) > 0) { // at least one waiting |
1459 |
> |
if (ws != null && (i = e & SMASK) < ws.length && |
1460 |
> |
(w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) { |
1461 |
> |
long nc = (((long)(w.nextWait & E_MASK)) | |
1462 |
> |
((long)(u + UAC_UNIT) << 32)); |
1463 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
1464 |
> |
w.eventCount = (e + E_SEQ) & E_MASK; |
1465 |
> |
if ((p = w.parker) != null) |
1466 |
> |
U.unpark(p); // activate and release |
1467 |
> |
break; |
1468 |
> |
} |
1469 |
> |
} |
1470 |
> |
else |
1471 |
> |
break; |
1472 |
> |
} |
1473 |
> |
else if (e == 0 && (u & SHORT_SIGN) != 0) { // too few total |
1474 |
> |
long nc = (long)(((u + UTC_UNIT) & UTC_MASK) | |
1475 |
> |
((u + UAC_UNIT) & UAC_MASK)) << 32; |
1476 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
1477 |
> |
addWorker(); |
1478 |
> |
break; |
1479 |
> |
} |
1480 |
|
} |
1481 |
+ |
else |
1482 |
+ |
break; |
1483 |
|
} |
1484 |
|
} |
1485 |
|
|
1486 |
+ |
|
1487 |
+ |
// Scanning for tasks |
1488 |
+ |
|
1489 |
|
/** |
1490 |
< |
* If worker is inactive, blocks until terminating or event count |
1491 |
< |
* advances from last value held by worker; in any case helps |
1492 |
< |
* release others. |
1493 |
< |
* |
1494 |
< |
* @param w the calling worker thread |
1495 |
< |
*/ |
1496 |
< |
private void eventSync(ForkJoinWorkerThread w) { |
1497 |
< |
if (!w.active) { |
1498 |
< |
int prev = w.lastEventCount; |
1499 |
< |
long nextTop = (((long)prev << EVENT_COUNT_SHIFT) | |
1500 |
< |
((long)(w.poolIndex + 1))); |
1501 |
< |
long top; |
1502 |
< |
while ((runState < SHUTDOWN || !tryTerminate(false)) && |
1503 |
< |
(((int)(top = eventWaiters) & WAITER_INDEX_MASK) == 0 || |
1504 |
< |
(int)(top >>> EVENT_COUNT_SHIFT) == prev) && |
1505 |
< |
eventCount == prev) { |
1506 |
< |
if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset, |
1507 |
< |
w.nextWaiter = top, nextTop)) { |
1508 |
< |
accumulateStealCount(w); // transfer steals while idle |
1509 |
< |
Thread.interrupted(); // clear/ignore interrupt |
1510 |
< |
while (eventCount == prev) |
1511 |
< |
w.doPark(); |
1490 |
> |
* Top-level runloop for workers, called by ForkJoinWorkerThread.run. |
1491 |
> |
*/ |
1492 |
> |
final void runWorker(WorkQueue w) { |
1493 |
> |
w.growArray(false); // initialize queue array in this thread |
1494 |
> |
do {} while (w.runTask(scan(w))); |
1495 |
> |
} |
1496 |
> |
|
1497 |
> |
/** |
1498 |
> |
* Scans for and, if found, returns one task, else possibly |
1499 |
> |
* inactivates the worker. This method operates on single reads of |
1500 |
> |
* volatile state and is designed to be re-invoked continuously, |
1501 |
> |
* in part because it returns upon detecting inconsistencies, |
1502 |
> |
* contention, or state changes that indicate possible success on |
1503 |
> |
* re-invocation. |
1504 |
> |
* |
1505 |
> |
* The scan searches for tasks across a random permutation of |
1506 |
> |
* queues (starting at a random index and stepping by a random |
1507 |
> |
* relative prime, checking each at least once). The scan |
1508 |
> |
* terminates upon either finding a non-empty queue, or completing |
1509 |
> |
* the sweep. If the worker is not inactivated, it takes and |
1510 |
> |
* returns a task from this queue. On failure to find a task, we |
1511 |
> |
* take one of the following actions, after which the caller will |
1512 |
> |
* retry calling this method unless terminated. |
1513 |
> |
* |
1514 |
> |
* * If pool is terminating, terminate the worker. |
1515 |
> |
* |
1516 |
> |
* * If not a complete sweep, try to release a waiting worker. If |
1517 |
> |
* the scan terminated because the worker is inactivated, then the |
1518 |
> |
* released worker will often be the calling worker, and it can |
1519 |
> |
* succeed obtaining a task on the next call. Or maybe it is |
1520 |
> |
* another worker, but with same net effect. Releasing in other |
1521 |
> |
* cases as well ensures that we have enough workers running. |
1522 |
> |
* |
1523 |
> |
* * If not already enqueued, try to inactivate and enqueue the |
1524 |
> |
* worker on wait queue. Or, if inactivating has caused the pool |
1525 |
> |
* to be quiescent, relay to idleAwaitWork to check for |
1526 |
> |
* termination and possibly shrink pool. |
1527 |
> |
* |
1528 |
> |
* * If already inactive, and the caller has run a task since the |
1529 |
> |
* last empty scan, return (to allow rescan) unless others are |
1530 |
> |
* also inactivated. Field WorkQueue.rescans counts down on each |
1531 |
> |
* scan to ensure eventual inactivation and blocking. |
1532 |
> |
* |
1533 |
> |
* * If already enqueued and none of the above apply, park |
1534 |
> |
* awaiting signal, |
1535 |
> |
* |
1536 |
> |
* @param w the worker (via its WorkQueue) |
1537 |
> |
* @return a task or null of none found |
1538 |
> |
*/ |
1539 |
> |
private final ForkJoinTask<?> scan(WorkQueue w) { |
1540 |
> |
WorkQueue[] ws; // first update random seed |
1541 |
> |
int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5; |
1542 |
> |
int rs = runState, m; // volatile read order matters |
1543 |
> |
if ((ws = workQueues) != null && (m = ws.length - 1) > 0) { |
1544 |
> |
int ec = w.eventCount; // ec is negative if inactive |
1545 |
> |
int step = (r >>> 16) | 1; // relative prime |
1546 |
> |
for (int j = (m + 1) << 2; ; r += step) { |
1547 |
> |
WorkQueue q; ForkJoinTask<?> t; ForkJoinTask<?>[] a; int b; |
1548 |
> |
if ((q = ws[r & m]) != null && (b = q.base) - q.top < 0 && |
1549 |
> |
(a = q.array) != null) { // probably nonempty |
1550 |
> |
int i = (((a.length - 1) & b) << ASHIFT) + ABASE; |
1551 |
> |
t = (ForkJoinTask<?>)U.getObjectVolatile(a, i); |
1552 |
> |
if (q.base == b && ec >= 0 && t != null && |
1553 |
> |
U.compareAndSwapObject(a, i, t, null)) { |
1554 |
> |
q.base = b + 1; // specialization of pollAt |
1555 |
> |
return t; |
1556 |
> |
} |
1557 |
> |
else if ((t != null || b + 1 != q.top) && |
1558 |
> |
(ec < 0 || j <= m)) { |
1559 |
> |
rs = 0; // mark scan as imcomplete |
1560 |
> |
break; // caller can retry after release |
1561 |
> |
} |
1562 |
> |
} |
1563 |
> |
if (--j < 0) |
1564 |
|
break; |
1565 |
+ |
} |
1566 |
+ |
long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns; |
1567 |
+ |
if (e < 0) // decode ctl on empty scan |
1568 |
+ |
w.runState = -1; // pool is terminating |
1569 |
+ |
else if (rs == 0 || rs != runState) { // incomplete scan |
1570 |
+ |
WorkQueue v; Thread p; // try to release a waiter |
1571 |
+ |
if (e > 0 && a < 0 && w.eventCount == ec && |
1572 |
+ |
(v = ws[e & m]) != null && v.eventCount == (e | INT_SIGN)) { |
1573 |
+ |
long nc = ((long)(v.nextWait & E_MASK) | |
1574 |
+ |
((c + AC_UNIT) & (AC_MASK|TC_MASK))); |
1575 |
+ |
if (ctl == c && U.compareAndSwapLong(this, CTL, c, nc)) { |
1576 |
+ |
v.eventCount = (e + E_SEQ) & E_MASK; |
1577 |
+ |
if ((p = v.parker) != null) |
1578 |
+ |
U.unpark(p); |
1579 |
+ |
} |
1580 |
+ |
} |
1581 |
+ |
} |
1582 |
+ |
else if (ec >= 0) { // try to enqueue/inactivate |
1583 |
+ |
long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK)); |
1584 |
+ |
w.nextWait = e; |
1585 |
+ |
w.eventCount = ec | INT_SIGN; // mark as inactive |
1586 |
+ |
if (ctl != c || !U.compareAndSwapLong(this, CTL, c, nc)) |
1587 |
+ |
w.eventCount = ec; // unmark on CAS failure |
1588 |
+ |
else { |
1589 |
+ |
if ((ns = w.nsteals) != 0) { |
1590 |
+ |
w.nsteals = 0; // set rescans if ran task |
1591 |
+ |
w.rescans = (a > 0) ? 0 : a + parallelism; |
1592 |
+ |
w.totalSteals += ns; |
1593 |
+ |
} |
1594 |
+ |
if (a == 1 - parallelism) // quiescent |
1595 |
+ |
idleAwaitWork(w, nc, c); |
1596 |
+ |
} |
1597 |
+ |
} |
1598 |
+ |
else if (w.eventCount < 0) { // already queued |
1599 |
+ |
if ((nr = w.rescans) > 0) { // continue rescanning |
1600 |
+ |
int ac = a + parallelism; |
1601 |
+ |
if (((w.rescans = (ac < nr) ? ac : nr - 1) & 3) == 0) |
1602 |
+ |
Thread.yield(); // yield before block |
1603 |
+ |
} |
1604 |
+ |
else { |
1605 |
+ |
Thread.interrupted(); // clear status |
1606 |
+ |
Thread wt = Thread.currentThread(); |
1607 |
+ |
U.putObject(wt, PARKBLOCKER, this); |
1608 |
+ |
w.parker = wt; // emulate LockSupport.park |
1609 |
+ |
if (w.eventCount < 0) // recheck |
1610 |
+ |
U.park(false, 0L); |
1611 |
+ |
w.parker = null; |
1612 |
+ |
U.putObject(wt, PARKBLOCKER, null); |
1613 |
|
} |
1614 |
|
} |
792 |
– |
w.lastEventCount = eventCount; |
1615 |
|
} |
1616 |
< |
releaseWaiters(); |
1616 |
> |
return null; |
1617 |
|
} |
1618 |
|
|
1619 |
|
/** |
1620 |
< |
* Callback from workers invoked upon each top-level action (i.e., |
1621 |
< |
* stealing a task or taking a submission and running |
1622 |
< |
* it). Performs one or both of the following: |
1623 |
< |
* |
1624 |
< |
* * If the worker cannot find work, updates its active status to |
1625 |
< |
* inactive and updates activeCount unless there is contention, in |
1626 |
< |
* which case it may try again (either in this or a subsequent |
1627 |
< |
* call). Additionally, awaits the next task event and/or helps |
1628 |
< |
* wake up other releasable waiters. |
1629 |
< |
* |
1630 |
< |
* * If there are too many running threads, suspends this worker |
1631 |
< |
* (first forcing inactivation if necessary). If it is not |
1632 |
< |
* resumed before a keepAlive elapses, the worker may be "trimmed" |
1633 |
< |
* -- killed while suspended within suspendAsSpare. Otherwise, |
1634 |
< |
* upon resume it rechecks to make sure that it is still needed. |
1635 |
< |
* |
1636 |
< |
* @param w the worker |
1637 |
< |
* @param worked false if the worker scanned for work but didn't |
1638 |
< |
* find any (in which case it may block waiting for work). |
1639 |
< |
*/ |
1640 |
< |
final void preStep(ForkJoinWorkerThread w, boolean worked) { |
1641 |
< |
boolean active = w.active; |
1642 |
< |
boolean inactivate = !worked & active; |
1643 |
< |
for (;;) { |
1644 |
< |
if (inactivate) { |
1645 |
< |
int c = runState; |
1646 |
< |
if (UNSAFE.compareAndSwapInt(this, runStateOffset, |
1647 |
< |
c, c - ONE_ACTIVE)) |
1648 |
< |
inactivate = active = w.active = false; |
1649 |
< |
} |
1650 |
< |
int wc = workerCounts; |
1651 |
< |
if ((wc & RUNNING_COUNT_MASK) <= parallelism) { |
1652 |
< |
if (!worked) |
831 |
< |
eventSync(w); |
832 |
< |
return; |
1620 |
> |
* If inactivating worker w has caused the pool to become |
1621 |
> |
* quiescent, checks for pool termination, and, so long as this is |
1622 |
> |
* not the only worker, waits for event for up to SHRINK_RATE |
1623 |
> |
* nanosecs. On timeout, if ctl has not changed, terminates the |
1624 |
> |
* worker, which will in turn wake up another worker to possibly |
1625 |
> |
* repeat this process. |
1626 |
> |
* |
1627 |
> |
* @param w the calling worker |
1628 |
> |
* @param currentCtl the ctl value triggering possible quiescence |
1629 |
> |
* @param prevCtl the ctl value to restore if thread is terminated |
1630 |
> |
*/ |
1631 |
> |
private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) { |
1632 |
> |
if (w.eventCount < 0 && !tryTerminate(false, false) && |
1633 |
> |
(int)prevCtl != 0 && ctl == currentCtl) { |
1634 |
> |
Thread wt = Thread.currentThread(); |
1635 |
> |
Thread.yield(); // yield before block |
1636 |
> |
while (ctl == currentCtl) { |
1637 |
> |
long startTime = System.nanoTime(); |
1638 |
> |
Thread.interrupted(); // timed variant of version in scan() |
1639 |
> |
U.putObject(wt, PARKBLOCKER, this); |
1640 |
> |
w.parker = wt; |
1641 |
> |
if (ctl == currentCtl) |
1642 |
> |
U.park(false, SHRINK_RATE); |
1643 |
> |
w.parker = null; |
1644 |
> |
U.putObject(wt, PARKBLOCKER, null); |
1645 |
> |
if (ctl != currentCtl) |
1646 |
> |
break; |
1647 |
> |
if (System.nanoTime() - startTime >= SHRINK_TIMEOUT && |
1648 |
> |
U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) { |
1649 |
> |
w.eventCount = (w.eventCount + E_SEQ) | E_MASK; |
1650 |
> |
w.runState = -1; // shrink |
1651 |
> |
break; |
1652 |
> |
} |
1653 |
|
} |
834 |
– |
if (!(inactivate |= active) && // must inactivate to suspend |
835 |
– |
UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
836 |
– |
wc, wc - ONE_RUNNING) && |
837 |
– |
!w.suspendAsSpare()) // false if trimmed |
838 |
– |
return; |
1654 |
|
} |
1655 |
|
} |
1656 |
|
|
1657 |
|
/** |
1658 |
< |
* Adjusts counts and creates or resumes compensating threads for |
1659 |
< |
* a worker about to block on task joinMe, returning early if |
1660 |
< |
* joinMe becomes ready. First tries resuming an existing spare |
1661 |
< |
* (which usually also avoids any count adjustment), but must then |
1662 |
< |
* decrement running count to determine whether a new thread is |
1663 |
< |
* needed. See above for fuller explanation. |
1664 |
< |
*/ |
1665 |
< |
final void preJoin(ForkJoinTask<?> joinMe) { |
1666 |
< |
boolean dec = false; // true when running count decremented |
1667 |
< |
for (;;) { |
1668 |
< |
releaseWaiters(); // help other threads progress |
1669 |
< |
|
1670 |
< |
if (joinMe.status < 0) // surround spare search with done checks |
1671 |
< |
return; |
1672 |
< |
ForkJoinWorkerThread spare = null; |
1673 |
< |
for (ForkJoinWorkerThread w : workers) { |
1674 |
< |
if (w != null && w.isSuspended()) { |
1675 |
< |
spare = w; |
1676 |
< |
break; |
1658 |
> |
* Tries to locate and execute tasks for a stealer of the given |
1659 |
> |
* task, or in turn one of its stealers, Traces currentSteal -> |
1660 |
> |
* currentJoin links looking for a thread working on a descendant |
1661 |
> |
* of the given task and with a non-empty queue to steal back and |
1662 |
> |
* execute tasks from. The first call to this method upon a |
1663 |
> |
* waiting join will often entail scanning/search, (which is OK |
1664 |
> |
* because the joiner has nothing better to do), but this method |
1665 |
> |
* leaves hints in workers to speed up subsequent calls. The |
1666 |
> |
* implementation is very branchy to cope with potential |
1667 |
> |
* inconsistencies or loops encountering chains that are stale, |
1668 |
> |
* unknown, or so long that they are likely cyclic. All of these |
1669 |
> |
* cases are dealt with by just retrying by caller. |
1670 |
> |
* |
1671 |
> |
* @param joiner the joining worker |
1672 |
> |
* @param task the task to join |
1673 |
> |
* @return true if found or ran a task (and so is immediately retryable) |
1674 |
> |
*/ |
1675 |
> |
private boolean tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) { |
1676 |
> |
WorkQueue[] ws; |
1677 |
> |
int m, depth = MAX_HELP; // remaining chain depth |
1678 |
> |
boolean progress = false; |
1679 |
> |
if ((ws = workQueues) != null && (m = ws.length - 1) > 0 && |
1680 |
> |
task.status >= 0) { |
1681 |
> |
ForkJoinTask<?> subtask = task; // current target |
1682 |
> |
outer: for (WorkQueue j = joiner;;) { |
1683 |
> |
WorkQueue stealer = null; // find stealer of subtask |
1684 |
> |
WorkQueue v = ws[j.stealHint & m]; // try hint |
1685 |
> |
if (v != null && v.currentSteal == subtask) |
1686 |
> |
stealer = v; |
1687 |
> |
else { // scan |
1688 |
> |
for (int i = 1; i <= m; i += 2) { |
1689 |
> |
if ((v = ws[i]) != null && v.currentSteal == subtask && |
1690 |
> |
v != joiner) { |
1691 |
> |
stealer = v; |
1692 |
> |
j.stealHint = i; // save hint |
1693 |
> |
break; |
1694 |
> |
} |
1695 |
> |
} |
1696 |
> |
if (stealer == null) |
1697 |
> |
break; |
1698 |
|
} |
863 |
– |
} |
864 |
– |
if (joinMe.status < 0) |
865 |
– |
return; |
1699 |
|
|
1700 |
< |
if (spare != null && spare.tryUnsuspend()) { |
1701 |
< |
if (dec || joinMe.requestSignal() < 0) { |
1702 |
< |
int c; |
1703 |
< |
do {} while (!UNSAFE.compareAndSwapInt(this, |
1704 |
< |
workerCountsOffset, |
1705 |
< |
c = workerCounts, |
1706 |
< |
c + ONE_RUNNING)); |
1707 |
< |
} // else no net count change |
1708 |
< |
LockSupport.unpark(spare); |
1709 |
< |
return; |
1710 |
< |
} |
1711 |
< |
|
1712 |
< |
int wc = workerCounts; // decrement running count |
1713 |
< |
if (!dec && (wc & RUNNING_COUNT_MASK) != 0 && |
1714 |
< |
(dec = UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
1715 |
< |
wc, wc -= ONE_RUNNING)) && |
1716 |
< |
joinMe.requestSignal() < 0) { // cannot block |
1717 |
< |
int c; // back out |
1718 |
< |
do {} while (!UNSAFE.compareAndSwapInt(this, |
1719 |
< |
workerCountsOffset, |
1720 |
< |
c = workerCounts, |
1721 |
< |
c + ONE_RUNNING)); |
1722 |
< |
return; |
1723 |
< |
} |
1724 |
< |
|
1725 |
< |
if (dec) { |
1726 |
< |
int tc = wc >>> TOTAL_COUNT_SHIFT; |
1727 |
< |
int pc = parallelism; |
895 |
< |
int dc = pc - (wc & RUNNING_COUNT_MASK); // deficit count |
896 |
< |
if ((dc < pc && (dc <= 0 || (dc * dc < (tc - pc) * pc) || |
897 |
< |
!maintainsParallelism)) || |
898 |
< |
tc >= maxPoolSize) // cannot add |
899 |
< |
return; |
900 |
< |
if (spare == null && |
901 |
< |
UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc, |
902 |
< |
wc + (ONE_RUNNING|ONE_TOTAL))) { |
903 |
< |
addWorker(); |
904 |
< |
return; |
1700 |
> |
for (WorkQueue q = stealer;;) { // try to help stealer |
1701 |
> |
ForkJoinTask[] a; ForkJoinTask<?> t; int b; |
1702 |
> |
if (task.status < 0) |
1703 |
> |
break outer; |
1704 |
> |
if ((b = q.base) - q.top < 0 && (a = q.array) != null) { |
1705 |
> |
progress = true; |
1706 |
> |
int i = (((a.length - 1) & b) << ASHIFT) + ABASE; |
1707 |
> |
t = (ForkJoinTask<?>)U.getObjectVolatile(a, i); |
1708 |
> |
if (subtask.status < 0) // must recheck before taking |
1709 |
> |
break outer; |
1710 |
> |
if (t != null && |
1711 |
> |
q.base == b && |
1712 |
> |
U.compareAndSwapObject(a, i, t, null)) { |
1713 |
> |
q.base = b + 1; |
1714 |
> |
joiner.runSubtask(t); |
1715 |
> |
} |
1716 |
> |
else if (q.base == b) |
1717 |
> |
break outer; // possibly stalled |
1718 |
> |
} |
1719 |
> |
else { // descend |
1720 |
> |
ForkJoinTask<?> next = stealer.currentJoin; |
1721 |
> |
if (--depth <= 0 || subtask.status < 0 || |
1722 |
> |
next == null || next == subtask) |
1723 |
> |
break outer; // stale, dead-end, or cyclic |
1724 |
> |
subtask = next; |
1725 |
> |
j = stealer; |
1726 |
> |
break; |
1727 |
> |
} |
1728 |
|
} |
1729 |
|
} |
1730 |
|
} |
1731 |
+ |
return progress; |
1732 |
|
} |
1733 |
|
|
1734 |
|
/** |
1735 |
< |
* Same idea as preJoin but with too many differing details to |
1736 |
< |
* integrate: There are no task-based signal counts, and only one |
1737 |
< |
* way to do the actual blocking. So for simplicity it is directly |
1738 |
< |
* incorporated into this method. |
1735 |
> |
* If task is at base of some steal queue, steals and executes it. |
1736 |
> |
* |
1737 |
> |
* @param joiner the joining worker |
1738 |
> |
* @param task the task |
1739 |
|
*/ |
1740 |
< |
final void doBlock(ManagedBlocker blocker, boolean maintainPar) |
1741 |
< |
throws InterruptedException { |
1742 |
< |
maintainPar &= maintainsParallelism; // override |
1743 |
< |
boolean dec = false; |
1744 |
< |
boolean done = false; |
1745 |
< |
for (;;) { |
1746 |
< |
releaseWaiters(); |
923 |
< |
if (done = blocker.isReleasable()) |
924 |
< |
break; |
925 |
< |
ForkJoinWorkerThread spare = null; |
926 |
< |
for (ForkJoinWorkerThread w : workers) { |
927 |
< |
if (w != null && w.isSuspended()) { |
928 |
< |
spare = w; |
1740 |
> |
private void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) { |
1741 |
> |
WorkQueue[] ws; |
1742 |
> |
if ((ws = workQueues) != null) { |
1743 |
> |
for (int j = 1; j < ws.length && task.status >= 0; j += 2) { |
1744 |
> |
WorkQueue q = ws[j]; |
1745 |
> |
if (q != null && q.pollFor(task)) { |
1746 |
> |
joiner.runSubtask(task); |
1747 |
|
break; |
1748 |
|
} |
1749 |
|
} |
1750 |
< |
if (done = blocker.isReleasable()) |
1751 |
< |
break; |
1752 |
< |
if (spare != null && spare.tryUnsuspend()) { |
1753 |
< |
if (dec) { |
1754 |
< |
int c; |
1755 |
< |
do {} while (!UNSAFE.compareAndSwapInt(this, |
1756 |
< |
workerCountsOffset, |
1757 |
< |
c = workerCounts, |
1758 |
< |
c + ONE_RUNNING)); |
1750 |
> |
} |
1751 |
> |
} |
1752 |
> |
|
1753 |
> |
/** |
1754 |
> |
* Tries to decrement active count (sometimes implicitly) and |
1755 |
> |
* possibly release or create a compensating worker in preparation |
1756 |
> |
* for blocking. Fails on contention or termination. Otherwise, |
1757 |
> |
* adds a new thread if no idle workers are available and either |
1758 |
> |
* pool would become completely starved or: (at least half |
1759 |
> |
* starved, and fewer than 50% spares exist, and there is at least |
1760 |
> |
* one task apparently available). Even though the availability |
1761 |
> |
* check requires a full scan, it is worthwhile in reducing false |
1762 |
> |
* alarms. |
1763 |
> |
* |
1764 |
> |
* @param task if nonnull, a task being waited for |
1765 |
> |
* @param blocker if nonnull, a blocker being waited for |
1766 |
> |
* @return true if the caller can block, else should recheck and retry |
1767 |
> |
*/ |
1768 |
> |
final boolean tryCompensate(ForkJoinTask<?> task, ManagedBlocker blocker) { |
1769 |
> |
int pc = parallelism, e; |
1770 |
> |
long c = ctl; |
1771 |
> |
WorkQueue[] ws = workQueues; |
1772 |
> |
if ((e = (int)c) >= 0 && ws != null) { |
1773 |
> |
int u, a, ac, hc; |
1774 |
> |
int tc = (short)((u = (int)(c >>> 32)) >>> UTC_SHIFT) + pc; |
1775 |
> |
boolean replace = false; |
1776 |
> |
if ((a = u >> UAC_SHIFT) <= 0) { |
1777 |
> |
if ((ac = a + pc) <= 1) |
1778 |
> |
replace = true; |
1779 |
> |
else if ((e > 0 || (task != null && |
1780 |
> |
ac <= (hc = pc >>> 1) && tc < pc + hc))) { |
1781 |
> |
WorkQueue w; |
1782 |
> |
for (int j = 0; j < ws.length; ++j) { |
1783 |
> |
if ((w = ws[j]) != null && !w.isEmpty()) { |
1784 |
> |
replace = true; |
1785 |
> |
break; // in compensation range and tasks available |
1786 |
> |
} |
1787 |
> |
} |
1788 |
|
} |
942 |
– |
LockSupport.unpark(spare); |
943 |
– |
break; |
1789 |
|
} |
1790 |
< |
int wc = workerCounts; |
1791 |
< |
if (!dec && (wc & RUNNING_COUNT_MASK) != 0) |
1792 |
< |
dec = UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
1793 |
< |
wc, wc -= ONE_RUNNING); |
1794 |
< |
if (dec) { |
1795 |
< |
int tc = wc >>> TOTAL_COUNT_SHIFT; |
1796 |
< |
int pc = parallelism; |
1797 |
< |
int dc = pc - (wc & RUNNING_COUNT_MASK); |
1798 |
< |
if ((dc < pc && (dc <= 0 || (dc * dc < (tc - pc) * pc) || |
1799 |
< |
!maintainPar)) || |
1800 |
< |
tc >= maxPoolSize) |
1801 |
< |
break; |
1802 |
< |
if (spare == null && |
1803 |
< |
UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc, |
1804 |
< |
wc + (ONE_RUNNING|ONE_TOTAL))){ |
1805 |
< |
addWorker(); |
1806 |
< |
break; |
1790 |
> |
if ((task == null || task.status >= 0) && // recheck need to block |
1791 |
> |
(blocker == null || !blocker.isReleasable()) && ctl == c) { |
1792 |
> |
if (!replace) { // no compensation |
1793 |
> |
long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK); |
1794 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) |
1795 |
> |
return true; |
1796 |
> |
} |
1797 |
> |
else if (e != 0) { // release an idle worker |
1798 |
> |
WorkQueue w; Thread p; int i; |
1799 |
> |
if ((i = e & SMASK) < ws.length && (w = ws[i]) != null) { |
1800 |
> |
long nc = ((long)(w.nextWait & E_MASK) | |
1801 |
> |
(c & (AC_MASK|TC_MASK))); |
1802 |
> |
if (w.eventCount == (e | INT_SIGN) && |
1803 |
> |
U.compareAndSwapLong(this, CTL, c, nc)) { |
1804 |
> |
w.eventCount = (e + E_SEQ) & E_MASK; |
1805 |
> |
if ((p = w.parker) != null) |
1806 |
> |
U.unpark(p); |
1807 |
> |
return true; |
1808 |
> |
} |
1809 |
> |
} |
1810 |
> |
} |
1811 |
> |
else if (tc < MAX_CAP) { // create replacement |
1812 |
> |
long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK); |
1813 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
1814 |
> |
addWorker(); |
1815 |
> |
return true; |
1816 |
> |
} |
1817 |
|
} |
1818 |
|
} |
1819 |
|
} |
1820 |
< |
|
966 |
< |
try { |
967 |
< |
if (!done) |
968 |
< |
do {} while (!blocker.isReleasable() && !blocker.block()); |
969 |
< |
} finally { |
970 |
< |
if (dec) { |
971 |
< |
int c; |
972 |
< |
do {} while (!UNSAFE.compareAndSwapInt(this, |
973 |
< |
workerCountsOffset, |
974 |
< |
c = workerCounts, |
975 |
< |
c + ONE_RUNNING)); |
976 |
< |
} |
977 |
< |
} |
1820 |
> |
return false; |
1821 |
|
} |
1822 |
|
|
1823 |
|
/** |
1824 |
< |
* Unless there are not enough other running threads, adjusts |
982 |
< |
* counts for a a worker in performing helpJoin that cannot find |
983 |
< |
* any work, so that this worker can now block. |
1824 |
> |
* Helps and/or blocks until the given task is done |
1825 |
|
* |
1826 |
< |
* @return true if worker may block |
1826 |
> |
* @param joiner the joining worker |
1827 |
> |
* @param task the task |
1828 |
> |
* @return task status on exit |
1829 |
|
*/ |
1830 |
< |
final boolean preBlockHelpingJoin(ForkJoinTask<?> joinMe) { |
1831 |
< |
while (joinMe.status >= 0) { |
1832 |
< |
releaseWaiters(); // help other threads progress |
1833 |
< |
|
1834 |
< |
// if a spare exists, resume it to maintain parallelism level |
1835 |
< |
if ((workerCounts & RUNNING_COUNT_MASK) <= parallelism) { |
1836 |
< |
ForkJoinWorkerThread spare = null; |
1837 |
< |
for (ForkJoinWorkerThread w : workers) { |
1838 |
< |
if (w != null && w.isSuspended()) { |
1839 |
< |
spare = w; |
1840 |
< |
break; |
998 |
< |
} |
1830 |
> |
final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) { |
1831 |
> |
ForkJoinTask<?> prevJoin = joiner.currentJoin; |
1832 |
> |
joiner.currentJoin = task; |
1833 |
> |
long startTime = 0L; |
1834 |
> |
for (int k = 0, s; ; ++k) { |
1835 |
> |
if ((joiner.isEmpty() ? // try to help |
1836 |
> |
!tryHelpStealer(joiner, task) : |
1837 |
> |
!joiner.tryRemoveAndExec(task))) { |
1838 |
> |
if (k == 0) { |
1839 |
> |
startTime = System.nanoTime(); |
1840 |
> |
tryPollForAndExec(joiner, task); // check uncommon case |
1841 |
|
} |
1842 |
< |
if (joinMe.status < 0) |
1843 |
< |
break; |
1844 |
< |
if (spare != null) { |
1845 |
< |
if (spare.tryUnsuspend()) { |
1846 |
< |
boolean canBlock = true; |
1847 |
< |
if (joinMe.requestSignal() < 0) { |
1848 |
< |
canBlock = false; // already done |
1849 |
< |
int c; |
1850 |
< |
do {} while (!UNSAFE.compareAndSwapInt |
1851 |
< |
(this, workerCountsOffset, |
1852 |
< |
c = workerCounts, c + ONE_RUNNING)); |
1842 |
> |
else if ((k & (MAX_HELP - 1)) == 0 && |
1843 |
> |
System.nanoTime() - startTime >= COMPENSATION_DELAY && |
1844 |
> |
tryCompensate(task, null)) { |
1845 |
> |
if (task.trySetSignal() && task.status >= 0) { |
1846 |
> |
synchronized (task) { |
1847 |
> |
if (task.status >= 0) { |
1848 |
> |
try { // see ForkJoinTask |
1849 |
> |
task.wait(); // for explanation |
1850 |
> |
} catch (InterruptedException ie) { |
1851 |
> |
} |
1852 |
> |
} |
1853 |
> |
else |
1854 |
> |
task.notifyAll(); |
1855 |
|
} |
1012 |
– |
LockSupport.unpark(spare); |
1013 |
– |
return canBlock; |
1856 |
|
} |
1857 |
< |
continue; // recheck -- another spare may exist |
1857 |
> |
long c; // re-activate |
1858 |
> |
do {} while (!U.compareAndSwapLong |
1859 |
> |
(this, CTL, c = ctl, c + AC_UNIT)); |
1860 |
|
} |
1861 |
|
} |
1862 |
< |
|
1863 |
< |
int wc = workerCounts; // reread to shorten CAS window |
1864 |
< |
int rc = wc & RUNNING_COUNT_MASK; |
1021 |
< |
if (rc <= 2) // keep this and at most one other thread alive |
1022 |
< |
break; |
1023 |
< |
|
1024 |
< |
if (UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
1025 |
< |
wc, wc - ONE_RUNNING)) { |
1026 |
< |
if (joinMe.requestSignal() >= 0) |
1027 |
< |
return true; |
1028 |
< |
int c; // back out |
1029 |
< |
do {} while (!UNSAFE.compareAndSwapInt |
1030 |
< |
(this, workerCountsOffset, |
1031 |
< |
c = workerCounts, c + ONE_RUNNING)); |
1032 |
< |
break; |
1862 |
> |
if ((s = task.status) < 0) { |
1863 |
> |
joiner.currentJoin = prevJoin; |
1864 |
> |
return s; |
1865 |
|
} |
1866 |
+ |
else if ((k & (MAX_HELP - 1)) == MAX_HELP >>> 1) |
1867 |
+ |
Thread.yield(); // for politeness |
1868 |
|
} |
1035 |
– |
return false; |
1869 |
|
} |
1870 |
|
|
1871 |
|
/** |
1872 |
< |
* Possibly initiates and/or completes termination. |
1872 |
> |
* Stripped-down variant of awaitJoin used by timed joins. Tries |
1873 |
> |
* to help join only while there is continuous progress. (Caller |
1874 |
> |
* will then enter a timed wait.) |
1875 |
|
* |
1876 |
< |
* @param now if true, unconditionally terminate, else only |
1877 |
< |
* if shutdown and empty queue and no active workers |
1878 |
< |
* @return true if now terminating or terminated |
1876 |
> |
* @param joiner the joining worker |
1877 |
> |
* @param task the task |
1878 |
> |
* @return task status on exit |
1879 |
|
*/ |
1880 |
< |
private boolean tryTerminate(boolean now) { |
1881 |
< |
if (now) |
1882 |
< |
advanceRunLevel(SHUTDOWN); // ensure at least SHUTDOWN |
1883 |
< |
else if (runState < SHUTDOWN || |
1884 |
< |
!submissionQueue.isEmpty() || |
1885 |
< |
(runState & ACTIVE_COUNT_MASK) != 0) |
1886 |
< |
return false; |
1887 |
< |
|
1053 |
< |
if (advanceRunLevel(TERMINATING)) |
1054 |
< |
startTerminating(); |
1055 |
< |
|
1056 |
< |
// Finish now if all threads terminated; else in some subsequent call |
1057 |
< |
if ((workerCounts >>> TOTAL_COUNT_SHIFT) == 0) { |
1058 |
< |
advanceRunLevel(TERMINATED); |
1059 |
< |
terminationLatch.countDown(); |
1060 |
< |
} |
1061 |
< |
return true; |
1880 |
> |
final int helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) { |
1881 |
> |
int s; |
1882 |
> |
while ((s = task.status) >= 0 && |
1883 |
> |
(joiner.isEmpty() ? |
1884 |
> |
tryHelpStealer(joiner, task) : |
1885 |
> |
joiner.tryRemoveAndExec(task))) |
1886 |
> |
; |
1887 |
> |
return s; |
1888 |
|
} |
1889 |
|
|
1890 |
|
/** |
1891 |
< |
* Actions on transition to TERMINATING |
1892 |
< |
*/ |
1893 |
< |
private void startTerminating() { |
1894 |
< |
// Clear out and cancel submissions, ignoring exceptions |
1895 |
< |
ForkJoinTask<?> task; |
1896 |
< |
while ((task = submissionQueue.poll()) != null) { |
1897 |
< |
try { |
1898 |
< |
task.cancel(false); |
1899 |
< |
} catch (Throwable ignore) { |
1900 |
< |
} |
1901 |
< |
} |
1902 |
< |
// Propagate run level |
1903 |
< |
for (ForkJoinWorkerThread w : workers) { |
1904 |
< |
if (w != null) |
1905 |
< |
w.shutdown(); // also resumes suspended workers |
1906 |
< |
} |
1907 |
< |
// Ensure no straggling local tasks |
1908 |
< |
for (ForkJoinWorkerThread w : workers) { |
1909 |
< |
if (w != null) |
1910 |
< |
w.cancelTasks(); |
1911 |
< |
} |
1086 |
< |
// Wake up idle workers |
1087 |
< |
advanceEventCount(); |
1088 |
< |
releaseWaiters(); |
1089 |
< |
// Unstick pending joins |
1090 |
< |
for (ForkJoinWorkerThread w : workers) { |
1091 |
< |
if (w != null && !w.isTerminated()) { |
1092 |
< |
try { |
1093 |
< |
w.interrupt(); |
1094 |
< |
} catch (SecurityException ignore) { |
1891 |
> |
* Returns a (probably) non-empty steal queue, if one is found |
1892 |
> |
* during a random, then cyclic scan, else null. This method must |
1893 |
> |
* be retried by caller if, by the time it tries to use the queue, |
1894 |
> |
* it is empty. |
1895 |
> |
*/ |
1896 |
> |
private WorkQueue findNonEmptyStealQueue(WorkQueue w) { |
1897 |
> |
// Similar to loop in scan(), but ignoring submissions |
1898 |
> |
int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5; |
1899 |
> |
int step = (r >>> 16) | 1; |
1900 |
> |
for (WorkQueue[] ws;;) { |
1901 |
> |
int rs = runState, m; |
1902 |
> |
if ((ws = workQueues) == null || (m = ws.length - 1) < 1) |
1903 |
> |
return null; |
1904 |
> |
for (int j = (m + 1) << 2; ; r += step) { |
1905 |
> |
WorkQueue q = ws[((r << 1) | 1) & m]; |
1906 |
> |
if (q != null && !q.isEmpty()) |
1907 |
> |
return q; |
1908 |
> |
else if (--j < 0) { |
1909 |
> |
if (runState == rs) |
1910 |
> |
return null; |
1911 |
> |
break; |
1912 |
|
} |
1913 |
|
} |
1914 |
|
} |
1915 |
|
} |
1916 |
|
|
1100 |
– |
// misc support for ForkJoinWorkerThread |
1101 |
– |
|
1917 |
|
/** |
1918 |
< |
* Returns pool number |
1919 |
< |
*/ |
1920 |
< |
final int getPoolNumber() { |
1921 |
< |
return poolNumber; |
1918 |
> |
* Runs tasks until {@code isQuiescent()}. We piggyback on |
1919 |
> |
* active count ctl maintenance, but rather than blocking |
1920 |
> |
* when tasks cannot be found, we rescan until all others cannot |
1921 |
> |
* find tasks either. |
1922 |
> |
*/ |
1923 |
> |
final void helpQuiescePool(WorkQueue w) { |
1924 |
> |
for (boolean active = true;;) { |
1925 |
> |
if (w.base - w.top < 0) |
1926 |
> |
w.runLocalTasks(); // exhaust local queue |
1927 |
> |
WorkQueue q = findNonEmptyStealQueue(w); |
1928 |
> |
if (q != null) { |
1929 |
> |
ForkJoinTask<?> t; int b; |
1930 |
> |
if (!active) { // re-establish active count |
1931 |
> |
long c; |
1932 |
> |
active = true; |
1933 |
> |
do {} while (!U.compareAndSwapLong |
1934 |
> |
(this, CTL, c = ctl, c + AC_UNIT)); |
1935 |
> |
} |
1936 |
> |
if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null) |
1937 |
> |
w.runSubtask(t); |
1938 |
> |
} |
1939 |
> |
else { |
1940 |
> |
long c; |
1941 |
> |
if (active) { // decrement active count without queuing |
1942 |
> |
active = false; |
1943 |
> |
do {} while (!U.compareAndSwapLong |
1944 |
> |
(this, CTL, c = ctl, c -= AC_UNIT)); |
1945 |
> |
} |
1946 |
> |
else |
1947 |
> |
c = ctl; // re-increment on exit |
1948 |
> |
if ((int)(c >> AC_SHIFT) + parallelism == 0) { |
1949 |
> |
do {} while (!U.compareAndSwapLong |
1950 |
> |
(this, CTL, c = ctl, c + AC_UNIT)); |
1951 |
> |
break; |
1952 |
> |
} |
1953 |
> |
} |
1954 |
> |
} |
1955 |
|
} |
1956 |
|
|
1957 |
|
/** |
1958 |
< |
* Accumulates steal count from a worker, clearing |
1959 |
< |
* the worker's value |
1958 |
> |
* Gets and removes a local or stolen task for the given worker. |
1959 |
> |
* |
1960 |
> |
* @return a task, if available |
1961 |
|
*/ |
1962 |
< |
final void accumulateStealCount(ForkJoinWorkerThread w) { |
1963 |
< |
int sc = w.stealCount; |
1964 |
< |
if (sc != 0) { |
1965 |
< |
long c; |
1966 |
< |
w.stealCount = 0; |
1967 |
< |
do {} while (!UNSAFE.compareAndSwapLong(this, stealCountOffset, |
1968 |
< |
c = stealCount, c + sc)); |
1962 |
> |
final ForkJoinTask<?> nextTaskFor(WorkQueue w) { |
1963 |
> |
for (ForkJoinTask<?> t;;) { |
1964 |
> |
WorkQueue q; int b; |
1965 |
> |
if ((t = w.nextLocalTask()) != null) |
1966 |
> |
return t; |
1967 |
> |
if ((q = findNonEmptyStealQueue(w)) == null) |
1968 |
> |
return null; |
1969 |
> |
if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null) |
1970 |
> |
return t; |
1971 |
|
} |
1972 |
|
} |
1973 |
|
|
1974 |
|
/** |
1975 |
|
* Returns the approximate (non-atomic) number of idle threads per |
1976 |
< |
* active thread. |
1976 |
> |
* active thread to offset steal queue size for method |
1977 |
> |
* ForkJoinTask.getSurplusQueuedTaskCount(). |
1978 |
|
*/ |
1979 |
|
final int idlePerActive() { |
1980 |
< |
int ac = runState; // no mask -- artifically boosts during shutdown |
1981 |
< |
int pc = parallelism; // use targeted parallelism, not rc |
1982 |
< |
// Use exact results for small values, saturate past 4 |
1983 |
< |
return pc <= ac? 0 : pc >>> 1 <= ac? 1 : pc >>> 2 <= ac? 3 : pc >>> 3; |
1980 |
> |
// Approximate at powers of two for small values, saturate past 4 |
1981 |
> |
int p = parallelism; |
1982 |
> |
int a = p + (int)(ctl >> AC_SHIFT); |
1983 |
> |
return (a > (p >>>= 1) ? 0 : |
1984 |
> |
a > (p >>>= 1) ? 1 : |
1985 |
> |
a > (p >>>= 1) ? 2 : |
1986 |
> |
a > (p >>>= 1) ? 4 : |
1987 |
> |
8); |
1988 |
> |
} |
1989 |
> |
|
1990 |
> |
// Termination |
1991 |
> |
|
1992 |
> |
/** |
1993 |
> |
* Possibly initiates and/or completes termination. The caller |
1994 |
> |
* triggering termination runs three passes through workQueues: |
1995 |
> |
* (0) Setting termination status, followed by wakeups of queued |
1996 |
> |
* workers; (1) cancelling all tasks; (2) interrupting lagging |
1997 |
> |
* threads (likely in external tasks, but possibly also blocked in |
1998 |
> |
* joins). Each pass repeats previous steps because of potential |
1999 |
> |
* lagging thread creation. |
2000 |
> |
* |
2001 |
> |
* @param now if true, unconditionally terminate, else only |
2002 |
> |
* if no work and no active workers |
2003 |
> |
* @param enable if true, enable shutdown when next possible |
2004 |
> |
* @return true if now terminating or terminated |
2005 |
> |
*/ |
2006 |
> |
private boolean tryTerminate(boolean now, boolean enable) { |
2007 |
> |
Mutex lock = this.lock; |
2008 |
> |
for (long c;;) { |
2009 |
> |
if (((c = ctl) & STOP_BIT) != 0) { // already terminating |
2010 |
> |
if ((short)(c >>> TC_SHIFT) == -parallelism) { |
2011 |
> |
lock.lock(); // don't need try/finally |
2012 |
> |
termination.signalAll(); // signal when 0 workers |
2013 |
> |
lock.unlock(); |
2014 |
> |
} |
2015 |
> |
return true; |
2016 |
> |
} |
2017 |
> |
if (runState >= 0) { // not yet enabled |
2018 |
> |
if (!enable) |
2019 |
> |
return false; |
2020 |
> |
lock.lock(); |
2021 |
> |
runState |= SHUTDOWN; |
2022 |
> |
lock.unlock(); |
2023 |
> |
} |
2024 |
> |
if (!now) { // check if idle & no tasks |
2025 |
> |
if ((int)(c >> AC_SHIFT) != -parallelism || |
2026 |
> |
hasQueuedSubmissions()) |
2027 |
> |
return false; |
2028 |
> |
// Check for unqueued inactive workers. One pass suffices. |
2029 |
> |
WorkQueue[] ws = workQueues; WorkQueue w; |
2030 |
> |
if (ws != null) { |
2031 |
> |
for (int i = 1; i < ws.length; i += 2) { |
2032 |
> |
if ((w = ws[i]) != null && w.eventCount >= 0) |
2033 |
> |
return false; |
2034 |
> |
} |
2035 |
> |
} |
2036 |
> |
} |
2037 |
> |
if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) { |
2038 |
> |
for (int pass = 0; pass < 3; ++pass) { |
2039 |
> |
WorkQueue[] ws = workQueues; |
2040 |
> |
if (ws != null) { |
2041 |
> |
WorkQueue w; |
2042 |
> |
int n = ws.length; |
2043 |
> |
for (int i = 0; i < n; ++i) { |
2044 |
> |
if ((w = ws[i]) != null) { |
2045 |
> |
w.runState = -1; |
2046 |
> |
if (pass > 0) { |
2047 |
> |
w.cancelAll(); |
2048 |
> |
if (pass > 1) |
2049 |
> |
w.interruptOwner(); |
2050 |
> |
} |
2051 |
> |
} |
2052 |
> |
} |
2053 |
> |
// Wake up workers parked on event queue |
2054 |
> |
int i, e; long cc; Thread p; |
2055 |
> |
while ((e = (int)(cc = ctl) & E_MASK) != 0 && |
2056 |
> |
(i = e & SMASK) < n && |
2057 |
> |
(w = ws[i]) != null) { |
2058 |
> |
long nc = ((long)(w.nextWait & E_MASK) | |
2059 |
> |
((cc + AC_UNIT) & AC_MASK) | |
2060 |
> |
(cc & (TC_MASK|STOP_BIT))); |
2061 |
> |
if (w.eventCount == (e | INT_SIGN) && |
2062 |
> |
U.compareAndSwapLong(this, CTL, cc, nc)) { |
2063 |
> |
w.eventCount = (e + E_SEQ) & E_MASK; |
2064 |
> |
w.runState = -1; |
2065 |
> |
if ((p = w.parker) != null) |
2066 |
> |
U.unpark(p); |
2067 |
> |
} |
2068 |
> |
} |
2069 |
> |
} |
2070 |
> |
} |
2071 |
> |
} |
2072 |
> |
} |
2073 |
|
} |
2074 |
|
|
2075 |
< |
// Public and protected methods |
2075 |
> |
// Exported methods |
2076 |
|
|
2077 |
|
// Constructors |
2078 |
|
|
2079 |
|
/** |
2080 |
|
* Creates a {@code ForkJoinPool} with parallelism equal to {@link |
2081 |
< |
* java.lang.Runtime#availableProcessors}, and using the {@linkplain |
2082 |
< |
* #defaultForkJoinWorkerThreadFactory default thread factory}. |
2081 |
> |
* java.lang.Runtime#availableProcessors}, using the {@linkplain |
2082 |
> |
* #defaultForkJoinWorkerThreadFactory default thread factory}, |
2083 |
> |
* no UncaughtExceptionHandler, and non-async LIFO processing mode. |
2084 |
|
* |
2085 |
|
* @throws SecurityException if a security manager exists and |
2086 |
|
* the caller is not permitted to modify threads |
2089 |
|
*/ |
2090 |
|
public ForkJoinPool() { |
2091 |
|
this(Runtime.getRuntime().availableProcessors(), |
2092 |
< |
defaultForkJoinWorkerThreadFactory); |
2092 |
> |
defaultForkJoinWorkerThreadFactory, null, false); |
2093 |
|
} |
2094 |
|
|
2095 |
|
/** |
2096 |
|
* Creates a {@code ForkJoinPool} with the indicated parallelism |
2097 |
< |
* level and using the {@linkplain |
2098 |
< |
* #defaultForkJoinWorkerThreadFactory default thread factory}. |
2097 |
> |
* level, the {@linkplain |
2098 |
> |
* #defaultForkJoinWorkerThreadFactory default thread factory}, |
2099 |
> |
* no UncaughtExceptionHandler, and non-async LIFO processing mode. |
2100 |
|
* |
2101 |
|
* @param parallelism the parallelism level |
2102 |
|
* @throws IllegalArgumentException if parallelism less than or |
2107 |
|
* java.lang.RuntimePermission}{@code ("modifyThread")} |
2108 |
|
*/ |
2109 |
|
public ForkJoinPool(int parallelism) { |
2110 |
< |
this(parallelism, defaultForkJoinWorkerThreadFactory); |
1168 |
< |
} |
1169 |
< |
|
1170 |
< |
/** |
1171 |
< |
* Creates a {@code ForkJoinPool} with parallelism equal to {@link |
1172 |
< |
* java.lang.Runtime#availableProcessors}, and using the given |
1173 |
< |
* thread factory. |
1174 |
< |
* |
1175 |
< |
* @param factory the factory for creating new threads |
1176 |
< |
* @throws NullPointerException if the factory is null |
1177 |
< |
* @throws SecurityException if a security manager exists and |
1178 |
< |
* the caller is not permitted to modify threads |
1179 |
< |
* because it does not hold {@link |
1180 |
< |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
1181 |
< |
*/ |
1182 |
< |
public ForkJoinPool(ForkJoinWorkerThreadFactory factory) { |
1183 |
< |
this(Runtime.getRuntime().availableProcessors(), factory); |
2110 |
> |
this(parallelism, defaultForkJoinWorkerThreadFactory, null, false); |
2111 |
|
} |
2112 |
|
|
2113 |
|
/** |
2114 |
< |
* Creates a {@code ForkJoinPool} with the given parallelism and |
1188 |
< |
* thread factory. |
2114 |
> |
* Creates a {@code ForkJoinPool} with the given parameters. |
2115 |
|
* |
2116 |
< |
* @param parallelism the parallelism level |
2117 |
< |
* @param factory the factory for creating new threads |
2116 |
> |
* @param parallelism the parallelism level. For default value, |
2117 |
> |
* use {@link java.lang.Runtime#availableProcessors}. |
2118 |
> |
* @param factory the factory for creating new threads. For default value, |
2119 |
> |
* use {@link #defaultForkJoinWorkerThreadFactory}. |
2120 |
> |
* @param handler the handler for internal worker threads that |
2121 |
> |
* terminate due to unrecoverable errors encountered while executing |
2122 |
> |
* tasks. For default value, use {@code null}. |
2123 |
> |
* @param asyncMode if true, |
2124 |
> |
* establishes local first-in-first-out scheduling mode for forked |
2125 |
> |
* tasks that are never joined. This mode may be more appropriate |
2126 |
> |
* than default locally stack-based mode in applications in which |
2127 |
> |
* worker threads only process event-style asynchronous tasks. |
2128 |
> |
* For default value, use {@code false}. |
2129 |
|
* @throws IllegalArgumentException if parallelism less than or |
2130 |
|
* equal to zero, or greater than implementation limit |
2131 |
|
* @throws NullPointerException if the factory is null |
2134 |
|
* because it does not hold {@link |
2135 |
|
* java.lang.RuntimePermission}{@code ("modifyThread")} |
2136 |
|
*/ |
2137 |
< |
public ForkJoinPool(int parallelism, ForkJoinWorkerThreadFactory factory) { |
2137 |
> |
public ForkJoinPool(int parallelism, |
2138 |
> |
ForkJoinWorkerThreadFactory factory, |
2139 |
> |
Thread.UncaughtExceptionHandler handler, |
2140 |
> |
boolean asyncMode) { |
2141 |
|
checkPermission(); |
2142 |
|
if (factory == null) |
2143 |
|
throw new NullPointerException(); |
2144 |
< |
if (parallelism <= 0 || parallelism > MAX_THREADS) |
2144 |
> |
if (parallelism <= 0 || parallelism > MAX_CAP) |
2145 |
|
throw new IllegalArgumentException(); |
1206 |
– |
this.poolNumber = poolNumberGenerator.incrementAndGet(); |
1207 |
– |
int arraySize = initialArraySizeFor(parallelism); |
2146 |
|
this.parallelism = parallelism; |
2147 |
|
this.factory = factory; |
2148 |
< |
this.maxPoolSize = MAX_THREADS; |
2149 |
< |
this.maintainsParallelism = true; |
2150 |
< |
this.workers = new ForkJoinWorkerThread[arraySize]; |
2151 |
< |
this.submissionQueue = new LinkedTransferQueue<ForkJoinTask<?>>(); |
2152 |
< |
this.workerLock = new ReentrantLock(); |
2153 |
< |
this.terminationLatch = new CountDownLatch(1); |
2154 |
< |
// Start first worker; remaining workers added upon first submission |
2155 |
< |
workerCounts = ONE_RUNNING | ONE_TOTAL; |
2156 |
< |
addWorker(); |
2157 |
< |
} |
2158 |
< |
|
2159 |
< |
/** |
2160 |
< |
* Returns initial power of two size for workers array. |
2161 |
< |
* @param pc the initial parallelism level |
2162 |
< |
*/ |
2163 |
< |
private static int initialArraySizeFor(int pc) { |
2164 |
< |
// See Hackers Delight, sec 3.2. We know MAX_THREADS < (1 >>> 16) |
2165 |
< |
int size = pc < MAX_THREADS ? pc + 1 : MAX_THREADS; |
2166 |
< |
size |= size >>> 1; |
2167 |
< |
size |= size >>> 2; |
2168 |
< |
size |= size >>> 4; |
1231 |
< |
size |= size >>> 8; |
1232 |
< |
return size + 1; |
2148 |
> |
this.ueh = handler; |
2149 |
> |
this.localMode = asyncMode ? FIFO_QUEUE : LIFO_QUEUE; |
2150 |
> |
long np = (long)(-parallelism); // offset ctl counts |
2151 |
> |
this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK); |
2152 |
> |
// Use nearest power 2 for workQueues size. See Hackers Delight sec 3.2. |
2153 |
> |
int n = parallelism - 1; |
2154 |
> |
n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; |
2155 |
> |
int size = (n + 1) << 1; // #slots = 2*#workers |
2156 |
> |
this.submitMask = size - 1; // room for max # of submit queues |
2157 |
> |
this.workQueues = new WorkQueue[size]; |
2158 |
> |
this.termination = (this.lock = new Mutex()).newCondition(); |
2159 |
> |
this.stealCount = new AtomicLong(); |
2160 |
> |
this.nextWorkerNumber = new AtomicInteger(); |
2161 |
> |
int pn = poolNumberGenerator.incrementAndGet(); |
2162 |
> |
StringBuilder sb = new StringBuilder("ForkJoinPool-"); |
2163 |
> |
sb.append(Integer.toString(pn)); |
2164 |
> |
sb.append("-worker-"); |
2165 |
> |
this.workerNamePrefix = sb.toString(); |
2166 |
> |
lock.lock(); |
2167 |
> |
this.runState = 1; // set init flag |
2168 |
> |
lock.unlock(); |
2169 |
|
} |
2170 |
|
|
2171 |
|
// Execution methods |
2172 |
|
|
2173 |
|
/** |
1238 |
– |
* Common code for execute, invoke and submit |
1239 |
– |
*/ |
1240 |
– |
private <T> void doSubmit(ForkJoinTask<T> task) { |
1241 |
– |
if (task == null) |
1242 |
– |
throw new NullPointerException(); |
1243 |
– |
if (runState >= SHUTDOWN) |
1244 |
– |
throw new RejectedExecutionException(); |
1245 |
– |
submissionQueue.offer(task); |
1246 |
– |
advanceEventCount(); |
1247 |
– |
releaseWaiters(); |
1248 |
– |
if ((workerCounts >>> TOTAL_COUNT_SHIFT) < parallelism) |
1249 |
– |
ensureEnoughTotalWorkers(); |
1250 |
– |
} |
1251 |
– |
|
1252 |
– |
/** |
2174 |
|
* Performs the given task, returning its result upon completion. |
2175 |
+ |
* If the computation encounters an unchecked Exception or Error, |
2176 |
+ |
* it is rethrown as the outcome of this invocation. Rethrown |
2177 |
+ |
* exceptions behave in the same way as regular exceptions, but, |
2178 |
+ |
* when possible, contain stack traces (as displayed for example |
2179 |
+ |
* using {@code ex.printStackTrace()}) of both the current thread |
2180 |
+ |
* as well as the thread actually encountering the exception; |
2181 |
+ |
* minimally only the latter. |
2182 |
|
* |
2183 |
|
* @param task the task |
2184 |
|
* @return the task's result |
2187 |
|
* scheduled for execution |
2188 |
|
*/ |
2189 |
|
public <T> T invoke(ForkJoinTask<T> task) { |
2190 |
+ |
if (task == null) |
2191 |
+ |
throw new NullPointerException(); |
2192 |
|
doSubmit(task); |
2193 |
|
return task.join(); |
2194 |
|
} |
2202 |
|
* scheduled for execution |
2203 |
|
*/ |
2204 |
|
public void execute(ForkJoinTask<?> task) { |
2205 |
+ |
if (task == null) |
2206 |
+ |
throw new NullPointerException(); |
2207 |
|
doSubmit(task); |
2208 |
|
} |
2209 |
|
|
2215 |
|
* scheduled for execution |
2216 |
|
*/ |
2217 |
|
public void execute(Runnable task) { |
2218 |
+ |
if (task == null) |
2219 |
+ |
throw new NullPointerException(); |
2220 |
|
ForkJoinTask<?> job; |
2221 |
|
if (task instanceof ForkJoinTask<?>) // avoid re-wrap |
2222 |
|
job = (ForkJoinTask<?>) task; |
2223 |
|
else |
2224 |
< |
job = ForkJoinTask.adapt(task, null); |
2224 |
> |
job = new ForkJoinTask.AdaptedRunnableAction(task); |
2225 |
|
doSubmit(job); |
2226 |
|
} |
2227 |
|
|
2228 |
|
/** |
2229 |
+ |
* Submits a ForkJoinTask for execution. |
2230 |
+ |
* |
2231 |
+ |
* @param task the task to submit |
2232 |
+ |
* @return the task |
2233 |
+ |
* @throws NullPointerException if the task is null |
2234 |
+ |
* @throws RejectedExecutionException if the task cannot be |
2235 |
+ |
* scheduled for execution |
2236 |
+ |
*/ |
2237 |
+ |
public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) { |
2238 |
+ |
if (task == null) |
2239 |
+ |
throw new NullPointerException(); |
2240 |
+ |
doSubmit(task); |
2241 |
+ |
return task; |
2242 |
+ |
} |
2243 |
+ |
|
2244 |
+ |
/** |
2245 |
|
* @throws NullPointerException if the task is null |
2246 |
|
* @throws RejectedExecutionException if the task cannot be |
2247 |
|
* scheduled for execution |
2248 |
|
*/ |
2249 |
|
public <T> ForkJoinTask<T> submit(Callable<T> task) { |
2250 |
< |
ForkJoinTask<T> job = ForkJoinTask.adapt(task); |
2250 |
> |
ForkJoinTask<T> job = new ForkJoinTask.AdaptedCallable<T>(task); |
2251 |
|
doSubmit(job); |
2252 |
|
return job; |
2253 |
|
} |
2258 |
|
* scheduled for execution |
2259 |
|
*/ |
2260 |
|
public <T> ForkJoinTask<T> submit(Runnable task, T result) { |
2261 |
< |
ForkJoinTask<T> job = ForkJoinTask.adapt(task, result); |
2261 |
> |
ForkJoinTask<T> job = new ForkJoinTask.AdaptedRunnable<T>(task, result); |
2262 |
|
doSubmit(job); |
2263 |
|
return job; |
2264 |
|
} |
2269 |
|
* scheduled for execution |
2270 |
|
*/ |
2271 |
|
public ForkJoinTask<?> submit(Runnable task) { |
2272 |
+ |
if (task == null) |
2273 |
+ |
throw new NullPointerException(); |
2274 |
|
ForkJoinTask<?> job; |
2275 |
|
if (task instanceof ForkJoinTask<?>) // avoid re-wrap |
2276 |
|
job = (ForkJoinTask<?>) task; |
2277 |
|
else |
2278 |
< |
job = ForkJoinTask.adapt(task, null); |
2278 |
> |
job = new ForkJoinTask.AdaptedRunnableAction(task); |
2279 |
|
doSubmit(job); |
2280 |
|
return job; |
2281 |
|
} |
2282 |
|
|
2283 |
|
/** |
1332 |
– |
* Submits a ForkJoinTask for execution. |
1333 |
– |
* |
1334 |
– |
* @param task the task to submit |
1335 |
– |
* @return the task |
1336 |
– |
* @throws NullPointerException if the task is null |
1337 |
– |
* @throws RejectedExecutionException if the task cannot be |
1338 |
– |
* scheduled for execution |
1339 |
– |
*/ |
1340 |
– |
public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) { |
1341 |
– |
doSubmit(task); |
1342 |
– |
return task; |
1343 |
– |
} |
1344 |
– |
|
1345 |
– |
/** |
2284 |
|
* @throws NullPointerException {@inheritDoc} |
2285 |
|
* @throws RejectedExecutionException {@inheritDoc} |
2286 |
|
*/ |
2287 |
|
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) { |
2288 |
< |
ArrayList<ForkJoinTask<T>> forkJoinTasks = |
2289 |
< |
new ArrayList<ForkJoinTask<T>>(tasks.size()); |
2290 |
< |
for (Callable<T> task : tasks) |
2291 |
< |
forkJoinTasks.add(ForkJoinTask.adapt(task)); |
2292 |
< |
invoke(new InvokeAll<T>(forkJoinTasks)); |
2293 |
< |
|
2288 |
> |
// In previous versions of this class, this method constructed |
2289 |
> |
// a task to run ForkJoinTask.invokeAll, but now external |
2290 |
> |
// invocation of multiple tasks is at least as efficient. |
2291 |
> |
List<ForkJoinTask<T>> fs = new ArrayList<ForkJoinTask<T>>(tasks.size()); |
2292 |
> |
// Workaround needed because method wasn't declared with |
2293 |
> |
// wildcards in return type but should have been. |
2294 |
|
@SuppressWarnings({"unchecked", "rawtypes"}) |
2295 |
< |
List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks; |
1358 |
< |
return futures; |
1359 |
< |
} |
2295 |
> |
List<Future<T>> futures = (List<Future<T>>) (List) fs; |
2296 |
|
|
2297 |
< |
static final class InvokeAll<T> extends RecursiveAction { |
2298 |
< |
final ArrayList<ForkJoinTask<T>> tasks; |
2299 |
< |
InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; } |
2300 |
< |
public void compute() { |
2301 |
< |
try { invokeAll(tasks); } |
2302 |
< |
catch (Exception ignore) {} |
2297 |
> |
boolean done = false; |
2298 |
> |
try { |
2299 |
> |
for (Callable<T> t : tasks) { |
2300 |
> |
ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t); |
2301 |
> |
doSubmit(f); |
2302 |
> |
fs.add(f); |
2303 |
> |
} |
2304 |
> |
for (ForkJoinTask<T> f : fs) |
2305 |
> |
f.quietlyJoin(); |
2306 |
> |
done = true; |
2307 |
> |
return futures; |
2308 |
> |
} finally { |
2309 |
> |
if (!done) |
2310 |
> |
for (ForkJoinTask<T> f : fs) |
2311 |
> |
f.cancel(false); |
2312 |
|
} |
1368 |
– |
private static final long serialVersionUID = -7914297376763021607L; |
2313 |
|
} |
2314 |
|
|
2315 |
|
/** |
2328 |
|
* @return the handler, or {@code null} if none |
2329 |
|
*/ |
2330 |
|
public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() { |
1387 |
– |
workerCountReadFence(); |
2331 |
|
return ueh; |
2332 |
|
} |
2333 |
|
|
2334 |
|
/** |
1392 |
– |
* Sets the handler for internal worker threads that terminate due |
1393 |
– |
* to unrecoverable errors encountered while executing tasks. |
1394 |
– |
* Unless set, the current default or ThreadGroup handler is used |
1395 |
– |
* as handler. |
1396 |
– |
* |
1397 |
– |
* @param h the new handler |
1398 |
– |
* @return the old handler, or {@code null} if none |
1399 |
– |
* @throws SecurityException if a security manager exists and |
1400 |
– |
* the caller is not permitted to modify threads |
1401 |
– |
* because it does not hold {@link |
1402 |
– |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
1403 |
– |
*/ |
1404 |
– |
public Thread.UncaughtExceptionHandler |
1405 |
– |
setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h) { |
1406 |
– |
checkPermission(); |
1407 |
– |
workerCountReadFence(); |
1408 |
– |
Thread.UncaughtExceptionHandler old = ueh; |
1409 |
– |
if (h != old) { |
1410 |
– |
ueh = h; |
1411 |
– |
workerCountWriteFence(); |
1412 |
– |
for (ForkJoinWorkerThread w : workers) { |
1413 |
– |
if (w != null) |
1414 |
– |
w.setUncaughtExceptionHandler(h); |
1415 |
– |
} |
1416 |
– |
} |
1417 |
– |
return old; |
1418 |
– |
} |
1419 |
– |
|
1420 |
– |
/** |
1421 |
– |
* Sets the target parallelism level of this pool. |
1422 |
– |
* |
1423 |
– |
* @param parallelism the target parallelism |
1424 |
– |
* @throws IllegalArgumentException if parallelism less than or |
1425 |
– |
* equal to zero or greater than maximum size bounds |
1426 |
– |
* @throws SecurityException if a security manager exists and |
1427 |
– |
* the caller is not permitted to modify threads |
1428 |
– |
* because it does not hold {@link |
1429 |
– |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
1430 |
– |
*/ |
1431 |
– |
public void setParallelism(int parallelism) { |
1432 |
– |
checkPermission(); |
1433 |
– |
if (parallelism <= 0 || parallelism > maxPoolSize) |
1434 |
– |
throw new IllegalArgumentException(); |
1435 |
– |
workerCountReadFence(); |
1436 |
– |
int pc = this.parallelism; |
1437 |
– |
if (pc != parallelism) { |
1438 |
– |
this.parallelism = parallelism; |
1439 |
– |
workerCountWriteFence(); |
1440 |
– |
// Release spares. If too many, some will die after re-suspend |
1441 |
– |
for (ForkJoinWorkerThread w : workers) { |
1442 |
– |
if (w != null && w.tryUnsuspend()) { |
1443 |
– |
updateRunningCount(1); |
1444 |
– |
LockSupport.unpark(w); |
1445 |
– |
} |
1446 |
– |
} |
1447 |
– |
ensureEnoughTotalWorkers(); |
1448 |
– |
advanceEventCount(); |
1449 |
– |
releaseWaiters(); // force config recheck by existing workers |
1450 |
– |
} |
1451 |
– |
} |
1452 |
– |
|
1453 |
– |
/** |
2335 |
|
* Returns the targeted parallelism level of this pool. |
2336 |
|
* |
2337 |
|
* @return the targeted parallelism level of this pool |
2338 |
|
*/ |
2339 |
|
public int getParallelism() { |
1459 |
– |
// workerCountReadFence(); // inlined below |
1460 |
– |
int ignore = workerCounts; |
2340 |
|
return parallelism; |
2341 |
|
} |
2342 |
|
|
2343 |
|
/** |
2344 |
|
* Returns the number of worker threads that have started but not |
2345 |
< |
* yet terminated. This result returned by this method may differ |
2345 |
> |
* yet terminated. The result returned by this method may differ |
2346 |
|
* from {@link #getParallelism} when threads are created to |
2347 |
|
* maintain parallelism when others are cooperatively blocked. |
2348 |
|
* |
2349 |
|
* @return the number of worker threads |
2350 |
|
*/ |
2351 |
|
public int getPoolSize() { |
2352 |
< |
return workerCounts >>> TOTAL_COUNT_SHIFT; |
1474 |
< |
} |
1475 |
< |
|
1476 |
< |
/** |
1477 |
< |
* Returns the maximum number of threads allowed to exist in the |
1478 |
< |
* pool. Unless set using {@link #setMaximumPoolSize}, the |
1479 |
< |
* maximum is an implementation-defined value designed only to |
1480 |
< |
* prevent runaway growth. |
1481 |
< |
* |
1482 |
< |
* @return the maximum |
1483 |
< |
*/ |
1484 |
< |
public int getMaximumPoolSize() { |
1485 |
< |
workerCountReadFence(); |
1486 |
< |
return maxPoolSize; |
1487 |
< |
} |
1488 |
< |
|
1489 |
< |
/** |
1490 |
< |
* Sets the maximum number of threads allowed to exist in the |
1491 |
< |
* pool. The given value should normally be greater than or equal |
1492 |
< |
* to the {@link #getParallelism parallelism} level. Setting this |
1493 |
< |
* value has no effect on current pool size. It controls |
1494 |
< |
* construction of new threads. The use of this method may cause |
1495 |
< |
* tasks that intrinsically require extra threads for dependent |
1496 |
< |
* computations to indefinitely stall. If you are instead trying |
1497 |
< |
* to minimize internal thread creation, consider setting {@link |
1498 |
< |
* #setMaintainsParallelism} as false. |
1499 |
< |
* |
1500 |
< |
* @throws IllegalArgumentException if negative or greater than |
1501 |
< |
* internal implementation limit |
1502 |
< |
*/ |
1503 |
< |
public void setMaximumPoolSize(int newMax) { |
1504 |
< |
if (newMax < 0 || newMax > MAX_THREADS) |
1505 |
< |
throw new IllegalArgumentException(); |
1506 |
< |
maxPoolSize = newMax; |
1507 |
< |
workerCountWriteFence(); |
1508 |
< |
} |
1509 |
< |
|
1510 |
< |
/** |
1511 |
< |
* Returns {@code true} if this pool dynamically maintains its |
1512 |
< |
* target parallelism level. If false, new threads are added only |
1513 |
< |
* to avoid possible starvation. This setting is by default true. |
1514 |
< |
* |
1515 |
< |
* @return {@code true} if maintains parallelism |
1516 |
< |
*/ |
1517 |
< |
public boolean getMaintainsParallelism() { |
1518 |
< |
workerCountReadFence(); |
1519 |
< |
return maintainsParallelism; |
1520 |
< |
} |
1521 |
< |
|
1522 |
< |
/** |
1523 |
< |
* Sets whether this pool dynamically maintains its target |
1524 |
< |
* parallelism level. If false, new threads are added only to |
1525 |
< |
* avoid possible starvation. |
1526 |
< |
* |
1527 |
< |
* @param enable {@code true} to maintain parallelism |
1528 |
< |
*/ |
1529 |
< |
public void setMaintainsParallelism(boolean enable) { |
1530 |
< |
maintainsParallelism = enable; |
1531 |
< |
workerCountWriteFence(); |
1532 |
< |
} |
1533 |
< |
|
1534 |
< |
/** |
1535 |
< |
* Establishes local first-in-first-out scheduling mode for forked |
1536 |
< |
* tasks that are never joined. This mode may be more appropriate |
1537 |
< |
* than default locally stack-based mode in applications in which |
1538 |
< |
* worker threads only process asynchronous tasks. This method is |
1539 |
< |
* designed to be invoked only when the pool is quiescent, and |
1540 |
< |
* typically only before any tasks are submitted. The effects of |
1541 |
< |
* invocations at other times may be unpredictable. |
1542 |
< |
* |
1543 |
< |
* @param async if {@code true}, use locally FIFO scheduling |
1544 |
< |
* @return the previous mode |
1545 |
< |
* @see #getAsyncMode |
1546 |
< |
*/ |
1547 |
< |
public boolean setAsyncMode(boolean async) { |
1548 |
< |
workerCountReadFence(); |
1549 |
< |
boolean oldMode = locallyFifo; |
1550 |
< |
if (oldMode != async) { |
1551 |
< |
locallyFifo = async; |
1552 |
< |
workerCountWriteFence(); |
1553 |
< |
for (ForkJoinWorkerThread w : workers) { |
1554 |
< |
if (w != null) |
1555 |
< |
w.setAsyncMode(async); |
1556 |
< |
} |
1557 |
< |
} |
1558 |
< |
return oldMode; |
2352 |
> |
return parallelism + (short)(ctl >>> TC_SHIFT); |
2353 |
|
} |
2354 |
|
|
2355 |
|
/** |
2357 |
|
* scheduling mode for forked tasks that are never joined. |
2358 |
|
* |
2359 |
|
* @return {@code true} if this pool uses async mode |
1566 |
– |
* @see #setAsyncMode |
2360 |
|
*/ |
2361 |
|
public boolean getAsyncMode() { |
2362 |
< |
workerCountReadFence(); |
1570 |
< |
return locallyFifo; |
2362 |
> |
return localMode != 0; |
2363 |
|
} |
2364 |
|
|
2365 |
|
/** |
2371 |
|
* @return the number of worker threads |
2372 |
|
*/ |
2373 |
|
public int getRunningThreadCount() { |
2374 |
< |
return workerCounts & RUNNING_COUNT_MASK; |
2374 |
> |
int rc = 0; |
2375 |
> |
WorkQueue[] ws; WorkQueue w; |
2376 |
> |
if ((ws = workQueues) != null) { |
2377 |
> |
for (int i = 1; i < ws.length; i += 2) { |
2378 |
> |
if ((w = ws[i]) != null && w.isApparentlyUnblocked()) |
2379 |
> |
++rc; |
2380 |
> |
} |
2381 |
> |
} |
2382 |
> |
return rc; |
2383 |
|
} |
2384 |
|
|
2385 |
|
/** |
2390 |
|
* @return the number of active threads |
2391 |
|
*/ |
2392 |
|
public int getActiveThreadCount() { |
2393 |
< |
return runState & ACTIVE_COUNT_MASK; |
2393 |
> |
int r = parallelism + (int)(ctl >> AC_SHIFT); |
2394 |
> |
return (r <= 0) ? 0 : r; // suppress momentarily negative values |
2395 |
|
} |
2396 |
|
|
2397 |
|
/** |
2406 |
|
* @return {@code true} if all threads are currently idle |
2407 |
|
*/ |
2408 |
|
public boolean isQuiescent() { |
2409 |
< |
return (runState & ACTIVE_COUNT_MASK) == 0; |
2409 |
> |
return (int)(ctl >> AC_SHIFT) + parallelism == 0; |
2410 |
|
} |
2411 |
|
|
2412 |
|
/** |
2421 |
|
* @return the number of steals |
2422 |
|
*/ |
2423 |
|
public long getStealCount() { |
2424 |
< |
return stealCount; |
2424 |
> |
long count = stealCount.get(); |
2425 |
> |
WorkQueue[] ws; WorkQueue w; |
2426 |
> |
if ((ws = workQueues) != null) { |
2427 |
> |
for (int i = 1; i < ws.length; i += 2) { |
2428 |
> |
if ((w = ws[i]) != null) |
2429 |
> |
count += w.totalSteals; |
2430 |
> |
} |
2431 |
> |
} |
2432 |
> |
return count; |
2433 |
|
} |
2434 |
|
|
2435 |
|
/** |
2444 |
|
*/ |
2445 |
|
public long getQueuedTaskCount() { |
2446 |
|
long count = 0; |
2447 |
< |
for (ForkJoinWorkerThread w : workers) { |
2448 |
< |
if (w != null) |
2449 |
< |
count += w.getQueueSize(); |
2447 |
> |
WorkQueue[] ws; WorkQueue w; |
2448 |
> |
if ((ws = workQueues) != null) { |
2449 |
> |
for (int i = 1; i < ws.length; i += 2) { |
2450 |
> |
if ((w = ws[i]) != null) |
2451 |
> |
count += w.queueSize(); |
2452 |
> |
} |
2453 |
|
} |
2454 |
|
return count; |
2455 |
|
} |
2456 |
|
|
2457 |
|
/** |
2458 |
|
* Returns an estimate of the number of tasks submitted to this |
2459 |
< |
* pool that have not yet begun executing. This method takes time |
2460 |
< |
* proportional to the number of submissions. |
2459 |
> |
* pool that have not yet begun executing. This method may take |
2460 |
> |
* time proportional to the number of submissions. |
2461 |
|
* |
2462 |
|
* @return the number of queued submissions |
2463 |
|
*/ |
2464 |
|
public int getQueuedSubmissionCount() { |
2465 |
< |
return submissionQueue.size(); |
2465 |
> |
int count = 0; |
2466 |
> |
WorkQueue[] ws; WorkQueue w; |
2467 |
> |
if ((ws = workQueues) != null) { |
2468 |
> |
for (int i = 0; i < ws.length; i += 2) { |
2469 |
> |
if ((w = ws[i]) != null) |
2470 |
> |
count += w.queueSize(); |
2471 |
> |
} |
2472 |
> |
} |
2473 |
> |
return count; |
2474 |
|
} |
2475 |
|
|
2476 |
|
/** |
2480 |
|
* @return {@code true} if there are any queued submissions |
2481 |
|
*/ |
2482 |
|
public boolean hasQueuedSubmissions() { |
2483 |
< |
return !submissionQueue.isEmpty(); |
2483 |
> |
WorkQueue[] ws; WorkQueue w; |
2484 |
> |
if ((ws = workQueues) != null) { |
2485 |
> |
for (int i = 0; i < ws.length; i += 2) { |
2486 |
> |
if ((w = ws[i]) != null && !w.isEmpty()) |
2487 |
> |
return true; |
2488 |
> |
} |
2489 |
> |
} |
2490 |
> |
return false; |
2491 |
|
} |
2492 |
|
|
2493 |
|
/** |
2498 |
|
* @return the next submission, or {@code null} if none |
2499 |
|
*/ |
2500 |
|
protected ForkJoinTask<?> pollSubmission() { |
2501 |
< |
return submissionQueue.poll(); |
2501 |
> |
WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t; |
2502 |
> |
if ((ws = workQueues) != null) { |
2503 |
> |
for (int i = 0; i < ws.length; i += 2) { |
2504 |
> |
if ((w = ws[i]) != null && (t = w.poll()) != null) |
2505 |
> |
return t; |
2506 |
> |
} |
2507 |
> |
} |
2508 |
> |
return null; |
2509 |
|
} |
2510 |
|
|
2511 |
|
/** |
2526 |
|
* @return the number of elements transferred |
2527 |
|
*/ |
2528 |
|
protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) { |
2529 |
< |
int n = submissionQueue.drainTo(c); |
2530 |
< |
for (ForkJoinWorkerThread w : workers) { |
2531 |
< |
if (w != null) |
2532 |
< |
n += w.drainTasksTo(c); |
2529 |
> |
int count = 0; |
2530 |
> |
WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t; |
2531 |
> |
if ((ws = workQueues) != null) { |
2532 |
> |
for (int i = 0; i < ws.length; ++i) { |
2533 |
> |
if ((w = ws[i]) != null) { |
2534 |
> |
while ((t = w.poll()) != null) { |
2535 |
> |
c.add(t); |
2536 |
> |
++count; |
2537 |
> |
} |
2538 |
> |
} |
2539 |
> |
} |
2540 |
|
} |
2541 |
< |
return n; |
2541 |
> |
return count; |
2542 |
|
} |
2543 |
|
|
2544 |
|
/** |
2549 |
|
* @return a string identifying this pool, as well as its state |
2550 |
|
*/ |
2551 |
|
public String toString() { |
2552 |
< |
long st = getStealCount(); |
2553 |
< |
long qt = getQueuedTaskCount(); |
2554 |
< |
long qs = getQueuedSubmissionCount(); |
2555 |
< |
int wc = workerCounts; |
2556 |
< |
int tc = wc >>> TOTAL_COUNT_SHIFT; |
2557 |
< |
int rc = wc & RUNNING_COUNT_MASK; |
2552 |
> |
// Use a single pass through workQueues to collect counts |
2553 |
> |
long qt = 0L, qs = 0L; int rc = 0; |
2554 |
> |
long st = stealCount.get(); |
2555 |
> |
long c = ctl; |
2556 |
> |
WorkQueue[] ws; WorkQueue w; |
2557 |
> |
if ((ws = workQueues) != null) { |
2558 |
> |
for (int i = 0; i < ws.length; ++i) { |
2559 |
> |
if ((w = ws[i]) != null) { |
2560 |
> |
int size = w.queueSize(); |
2561 |
> |
if ((i & 1) == 0) |
2562 |
> |
qs += size; |
2563 |
> |
else { |
2564 |
> |
qt += size; |
2565 |
> |
st += w.totalSteals; |
2566 |
> |
if (w.isApparentlyUnblocked()) |
2567 |
> |
++rc; |
2568 |
> |
} |
2569 |
> |
} |
2570 |
> |
} |
2571 |
> |
} |
2572 |
|
int pc = parallelism; |
2573 |
< |
int rs = runState; |
2574 |
< |
int ac = rs & ACTIVE_COUNT_MASK; |
2573 |
> |
int tc = pc + (short)(c >>> TC_SHIFT); |
2574 |
> |
int ac = pc + (int)(c >> AC_SHIFT); |
2575 |
> |
if (ac < 0) // ignore transient negative |
2576 |
> |
ac = 0; |
2577 |
> |
String level; |
2578 |
> |
if ((c & STOP_BIT) != 0) |
2579 |
> |
level = (tc == 0) ? "Terminated" : "Terminating"; |
2580 |
> |
else |
2581 |
> |
level = runState < 0 ? "Shutting down" : "Running"; |
2582 |
|
return super.toString() + |
2583 |
< |
"[" + runLevelToString(rs) + |
2583 |
> |
"[" + level + |
2584 |
|
", parallelism = " + pc + |
2585 |
|
", size = " + tc + |
2586 |
|
", active = " + ac + |
2591 |
|
"]"; |
2592 |
|
} |
2593 |
|
|
1732 |
– |
private static String runLevelToString(int s) { |
1733 |
– |
return ((s & TERMINATED) != 0 ? "Terminated" : |
1734 |
– |
((s & TERMINATING) != 0 ? "Terminating" : |
1735 |
– |
((s & SHUTDOWN) != 0 ? "Shutting down" : |
1736 |
– |
"Running"))); |
1737 |
– |
} |
1738 |
– |
|
2594 |
|
/** |
2595 |
|
* Initiates an orderly shutdown in which previously submitted |
2596 |
|
* tasks are executed, but no new tasks will be accepted. |
2605 |
|
*/ |
2606 |
|
public void shutdown() { |
2607 |
|
checkPermission(); |
2608 |
< |
advanceRunLevel(SHUTDOWN); |
1754 |
< |
tryTerminate(false); |
2608 |
> |
tryTerminate(false, true); |
2609 |
|
} |
2610 |
|
|
2611 |
|
/** |
2626 |
|
*/ |
2627 |
|
public List<Runnable> shutdownNow() { |
2628 |
|
checkPermission(); |
2629 |
< |
tryTerminate(true); |
2629 |
> |
tryTerminate(true, true); |
2630 |
|
return Collections.emptyList(); |
2631 |
|
} |
2632 |
|
|
2636 |
|
* @return {@code true} if all tasks have completed following shut down |
2637 |
|
*/ |
2638 |
|
public boolean isTerminated() { |
2639 |
< |
return runState >= TERMINATED; |
2639 |
> |
long c = ctl; |
2640 |
> |
return ((c & STOP_BIT) != 0L && |
2641 |
> |
(short)(c >>> TC_SHIFT) == -parallelism); |
2642 |
|
} |
2643 |
|
|
2644 |
|
/** |
2646 |
|
* commenced but not yet completed. This method may be useful for |
2647 |
|
* debugging. A return of {@code true} reported a sufficient |
2648 |
|
* period after shutdown may indicate that submitted tasks have |
2649 |
< |
* ignored or suppressed interruption, causing this executor not |
2650 |
< |
* to properly terminate. |
2649 |
> |
* ignored or suppressed interruption, or are waiting for IO, |
2650 |
> |
* causing this executor not to properly terminate. (See the |
2651 |
> |
* advisory notes for class {@link ForkJoinTask} stating that |
2652 |
> |
* tasks should not normally entail blocking operations. But if |
2653 |
> |
* they do, they must abort them on interrupt.) |
2654 |
|
* |
2655 |
|
* @return {@code true} if terminating but not yet terminated |
2656 |
|
*/ |
2657 |
|
public boolean isTerminating() { |
2658 |
< |
return (runState & (TERMINATING|TERMINATED)) == TERMINATING; |
2658 |
> |
long c = ctl; |
2659 |
> |
return ((c & STOP_BIT) != 0L && |
2660 |
> |
(short)(c >>> TC_SHIFT) != -parallelism); |
2661 |
|
} |
2662 |
|
|
2663 |
|
/** |
2666 |
|
* @return {@code true} if this pool has been shut down |
2667 |
|
*/ |
2668 |
|
public boolean isShutdown() { |
2669 |
< |
return runState >= SHUTDOWN; |
2669 |
> |
return runState < 0; |
2670 |
|
} |
2671 |
|
|
2672 |
|
/** |
2682 |
|
*/ |
2683 |
|
public boolean awaitTermination(long timeout, TimeUnit unit) |
2684 |
|
throws InterruptedException { |
2685 |
< |
return terminationLatch.await(timeout, unit); |
2685 |
> |
long nanos = unit.toNanos(timeout); |
2686 |
> |
final Mutex lock = this.lock; |
2687 |
> |
lock.lock(); |
2688 |
> |
try { |
2689 |
> |
for (;;) { |
2690 |
> |
if (isTerminated()) |
2691 |
> |
return true; |
2692 |
> |
if (nanos <= 0) |
2693 |
> |
return false; |
2694 |
> |
nanos = termination.awaitNanos(nanos); |
2695 |
> |
} |
2696 |
> |
} finally { |
2697 |
> |
lock.unlock(); |
2698 |
> |
} |
2699 |
|
} |
2700 |
|
|
2701 |
|
/** |
2702 |
|
* Interface for extending managed parallelism for tasks running |
2703 |
|
* in {@link ForkJoinPool}s. |
2704 |
|
* |
2705 |
< |
* <p>A {@code ManagedBlocker} provides two methods. |
2706 |
< |
* Method {@code isReleasable} must return {@code true} if |
2707 |
< |
* blocking is not necessary. Method {@code block} blocks the |
2708 |
< |
* current thread if necessary (perhaps internally invoking |
2709 |
< |
* {@code isReleasable} before actually blocking). |
2705 |
> |
* <p>A {@code ManagedBlocker} provides two methods. Method |
2706 |
> |
* {@code isReleasable} must return {@code true} if blocking is |
2707 |
> |
* not necessary. Method {@code block} blocks the current thread |
2708 |
> |
* if necessary (perhaps internally invoking {@code isReleasable} |
2709 |
> |
* before actually blocking). These actions are performed by any |
2710 |
> |
* thread invoking {@link ForkJoinPool#managedBlock}. The |
2711 |
> |
* unusual methods in this API accommodate synchronizers that may, |
2712 |
> |
* but don't usually, block for long periods. Similarly, they |
2713 |
> |
* allow more efficient internal handling of cases in which |
2714 |
> |
* additional workers may be, but usually are not, needed to |
2715 |
> |
* ensure sufficient parallelism. Toward this end, |
2716 |
> |
* implementations of method {@code isReleasable} must be amenable |
2717 |
> |
* to repeated invocation. |
2718 |
|
* |
2719 |
|
* <p>For example, here is a ManagedBlocker based on a |
2720 |
|
* ReentrantLock: |
2732 |
|
* return hasLock || (hasLock = lock.tryLock()); |
2733 |
|
* } |
2734 |
|
* }}</pre> |
2735 |
+ |
* |
2736 |
+ |
* <p>Here is a class that possibly blocks waiting for an |
2737 |
+ |
* item on a given queue: |
2738 |
+ |
* <pre> {@code |
2739 |
+ |
* class QueueTaker<E> implements ManagedBlocker { |
2740 |
+ |
* final BlockingQueue<E> queue; |
2741 |
+ |
* volatile E item = null; |
2742 |
+ |
* QueueTaker(BlockingQueue<E> q) { this.queue = q; } |
2743 |
+ |
* public boolean block() throws InterruptedException { |
2744 |
+ |
* if (item == null) |
2745 |
+ |
* item = queue.take(); |
2746 |
+ |
* return true; |
2747 |
+ |
* } |
2748 |
+ |
* public boolean isReleasable() { |
2749 |
+ |
* return item != null || (item = queue.poll()) != null; |
2750 |
+ |
* } |
2751 |
+ |
* public E getItem() { // call after pool.managedBlock completes |
2752 |
+ |
* return item; |
2753 |
+ |
* } |
2754 |
+ |
* }}</pre> |
2755 |
|
*/ |
2756 |
|
public static interface ManagedBlocker { |
2757 |
|
/** |
2775 |
|
* Blocks in accord with the given blocker. If the current thread |
2776 |
|
* is a {@link ForkJoinWorkerThread}, this method possibly |
2777 |
|
* arranges for a spare thread to be activated if necessary to |
2778 |
< |
* ensure parallelism while the current thread is blocked. |
1877 |
< |
* |
1878 |
< |
* <p>If {@code maintainParallelism} is {@code true} and the pool |
1879 |
< |
* supports it ({@link #getMaintainsParallelism}), this method |
1880 |
< |
* attempts to maintain the pool's nominal parallelism. Otherwise |
1881 |
< |
* it activates a thread only if necessary to avoid complete |
1882 |
< |
* starvation. This option may be preferable when blockages use |
1883 |
< |
* timeouts, or are almost always brief. |
2778 |
> |
* ensure sufficient parallelism while the current thread is blocked. |
2779 |
|
* |
2780 |
|
* <p>If the caller is not a {@link ForkJoinTask}, this method is |
2781 |
|
* behaviorally equivalent to |
2789 |
|
* first be expanded to ensure parallelism, and later adjusted. |
2790 |
|
* |
2791 |
|
* @param blocker the blocker |
1897 |
– |
* @param maintainParallelism if {@code true} and supported by |
1898 |
– |
* this pool, attempt to maintain the pool's nominal parallelism; |
1899 |
– |
* otherwise activate a thread only if necessary to avoid |
1900 |
– |
* complete starvation. |
2792 |
|
* @throws InterruptedException if blocker.block did so |
2793 |
|
*/ |
2794 |
< |
public static void managedBlock(ManagedBlocker blocker, |
1904 |
< |
boolean maintainParallelism) |
2794 |
> |
public static void managedBlock(ManagedBlocker blocker) |
2795 |
|
throws InterruptedException { |
2796 |
|
Thread t = Thread.currentThread(); |
2797 |
< |
if (t instanceof ForkJoinWorkerThread) |
2798 |
< |
((ForkJoinWorkerThread) t).pool. |
2799 |
< |
doBlock(blocker, maintainParallelism); |
2800 |
< |
else |
2801 |
< |
awaitBlocker(blocker); |
2802 |
< |
} |
2803 |
< |
|
2804 |
< |
/** |
2805 |
< |
* Performs Non-FJ blocking |
2806 |
< |
*/ |
2807 |
< |
private static void awaitBlocker(ManagedBlocker blocker) |
2808 |
< |
throws InterruptedException { |
2809 |
< |
do {} while (!blocker.isReleasable() && !blocker.block()); |
2797 |
> |
ForkJoinPool p = ((t instanceof ForkJoinWorkerThread) ? |
2798 |
> |
((ForkJoinWorkerThread)t).pool : null); |
2799 |
> |
while (!blocker.isReleasable()) { |
2800 |
> |
if (p == null || p.tryCompensate(null, blocker)) { |
2801 |
> |
try { |
2802 |
> |
do {} while (!blocker.isReleasable() && !blocker.block()); |
2803 |
> |
} finally { |
2804 |
> |
if (p != null) |
2805 |
> |
p.incrementActiveCount(); |
2806 |
> |
} |
2807 |
> |
break; |
2808 |
> |
} |
2809 |
> |
} |
2810 |
|
} |
2811 |
|
|
2812 |
|
// AbstractExecutorService overrides. These rely on undocumented |
2814 |
|
// implement RunnableFuture. |
2815 |
|
|
2816 |
|
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) { |
2817 |
< |
return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value); |
2817 |
> |
return new ForkJoinTask.AdaptedRunnable<T>(runnable, value); |
2818 |
|
} |
2819 |
|
|
2820 |
|
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) { |
2821 |
< |
return (RunnableFuture<T>) ForkJoinTask.adapt(callable); |
2821 |
> |
return new ForkJoinTask.AdaptedCallable<T>(callable); |
2822 |
|
} |
2823 |
|
|
2824 |
|
// Unsafe mechanics |
2825 |
< |
|
2826 |
< |
private static final sun.misc.Unsafe UNSAFE = getUnsafe(); |
2827 |
< |
private static final long workerCountsOffset = |
2828 |
< |
objectFieldOffset("workerCounts", ForkJoinPool.class); |
2829 |
< |
private static final long runStateOffset = |
2830 |
< |
objectFieldOffset("runState", ForkJoinPool.class); |
2831 |
< |
private static final long eventCountOffset = |
2832 |
< |
objectFieldOffset("eventCount", ForkJoinPool.class); |
2833 |
< |
private static final long eventWaitersOffset = |
2834 |
< |
objectFieldOffset("eventWaiters",ForkJoinPool.class); |
2835 |
< |
private static final long stealCountOffset = |
2836 |
< |
objectFieldOffset("stealCount",ForkJoinPool.class); |
2837 |
< |
|
2838 |
< |
|
1949 |
< |
private static long objectFieldOffset(String field, Class<?> klazz) { |
2825 |
> |
private static final sun.misc.Unsafe U; |
2826 |
> |
private static final long CTL; |
2827 |
> |
private static final long PARKBLOCKER; |
2828 |
> |
private static final int ABASE; |
2829 |
> |
private static final int ASHIFT; |
2830 |
> |
|
2831 |
> |
static { |
2832 |
> |
poolNumberGenerator = new AtomicInteger(); |
2833 |
> |
nextSubmitterSeed = new AtomicInteger(0x55555555); |
2834 |
> |
modifyThreadPermission = new RuntimePermission("modifyThread"); |
2835 |
> |
defaultForkJoinWorkerThreadFactory = |
2836 |
> |
new DefaultForkJoinWorkerThreadFactory(); |
2837 |
> |
submitters = new ThreadSubmitter(); |
2838 |
> |
int s; |
2839 |
|
try { |
2840 |
< |
return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field)); |
2841 |
< |
} catch (NoSuchFieldException e) { |
2842 |
< |
// Convert Exception to corresponding Error |
2843 |
< |
NoSuchFieldError error = new NoSuchFieldError(field); |
2844 |
< |
error.initCause(e); |
2845 |
< |
throw error; |
2846 |
< |
} |
2840 |
> |
U = getUnsafe(); |
2841 |
> |
Class<?> k = ForkJoinPool.class; |
2842 |
> |
Class<?> ak = ForkJoinTask[].class; |
2843 |
> |
CTL = U.objectFieldOffset |
2844 |
> |
(k.getDeclaredField("ctl")); |
2845 |
> |
Class<?> tk = Thread.class; |
2846 |
> |
PARKBLOCKER = U.objectFieldOffset |
2847 |
> |
(tk.getDeclaredField("parkBlocker")); |
2848 |
> |
ABASE = U.arrayBaseOffset(ak); |
2849 |
> |
s = U.arrayIndexScale(ak); |
2850 |
> |
} catch (Exception e) { |
2851 |
> |
throw new Error(e); |
2852 |
> |
} |
2853 |
> |
if ((s & (s-1)) != 0) |
2854 |
> |
throw new Error("data type scale not a power of two"); |
2855 |
> |
ASHIFT = 31 - Integer.numberOfLeadingZeros(s); |
2856 |
|
} |
2857 |
|
|
2858 |
|
/** |
2882 |
|
} |
2883 |
|
} |
2884 |
|
} |
2885 |
+ |
|
2886 |
|
} |