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