20 |
|
import java.util.concurrent.RunnableFuture; |
21 |
|
import java.util.concurrent.TimeUnit; |
22 |
|
import java.util.concurrent.atomic.AtomicInteger; |
23 |
< |
import java.util.concurrent.locks.LockSupport; |
24 |
< |
import java.util.concurrent.locks.ReentrantLock; |
23 |
> |
import java.util.concurrent.atomic.AtomicLong; |
24 |
> |
import java.util.concurrent.locks.AbstractQueuedSynchronizer; |
25 |
|
import java.util.concurrent.locks.Condition; |
26 |
|
|
27 |
|
/** |
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 used by any ForkJoinTask that |
47 |
> |
* is not explicitly submitted to a specified pool. Using the common |
48 |
> |
* pool normally reduces resource usage (its threads are slowly |
49 |
> |
* reclaimed during periods of non-use, and reinstated upon subsequent |
50 |
> |
* use). The common pool is by default constructed with default |
51 |
> |
* parameters, but these may be controlled by setting any or all of |
52 |
> |
* the three properties {@code |
53 |
> |
* java.util.concurrent.ForkJoinPool.common.{parallelism, |
54 |
> |
* threadFactory, exceptionHandler}}. |
55 |
> |
* |
56 |
> |
* <p>For applications that require separate or custom pools, a {@code |
57 |
> |
* ForkJoinPool} may be constructed with a given target parallelism |
58 |
> |
* level; by default, equal to the number of available processors. The |
59 |
> |
* pool attempts to maintain enough active (or available) threads by |
60 |
> |
* dynamically adding, suspending, or resuming internal worker |
61 |
> |
* threads, even if some tasks are stalled waiting to join |
62 |
> |
* others. However, no such adjustments are guaranteed in the face of |
63 |
> |
* blocked IO or other unmanaged synchronization. The nested {@link |
64 |
> |
* ManagedBlocker} interface enables extension of the kinds of |
65 |
|
* synchronization accommodated. |
66 |
|
* |
67 |
|
* <p>In addition to execution and lifecycle control methods, this |
72 |
|
* convenient form for informal monitoring. |
73 |
|
* |
74 |
|
* <p> As is the case with other ExecutorServices, there are three |
75 |
< |
* main task execution methods summarized in the following |
76 |
< |
* table. These are designed to be used by clients not already engaged |
77 |
< |
* in fork/join computations in the current pool. The main forms of |
78 |
< |
* these methods accept instances of {@code ForkJoinTask}, but |
79 |
< |
* overloaded forms also allow mixed execution of plain {@code |
75 |
> |
* main task execution methods summarized in the following table. |
76 |
> |
* These are designed to be used primarily by clients not already |
77 |
> |
* engaged in fork/join computations in the current pool. The main |
78 |
> |
* forms of these methods accept instances of {@code ForkJoinTask}, |
79 |
> |
* but overloaded forms also allow mixed execution of plain {@code |
80 |
|
* Runnable}- or {@code Callable}- based activities as well. However, |
81 |
< |
* tasks that are already executing in a pool should normally |
82 |
< |
* <em>NOT</em> use these pool execution methods, but instead use the |
83 |
< |
* within-computation forms listed in the table. |
81 |
> |
* tasks that are already executing in a pool should normally instead |
82 |
> |
* use the within-computation forms listed in the table unless using |
83 |
> |
* async event-style tasks that are not usually joined, in which case |
84 |
> |
* there is little difference among choice of methods. |
85 |
|
* |
86 |
|
* <table BORDER CELLPADDING=3 CELLSPACING=1> |
87 |
|
* <tr> |
106 |
|
* </tr> |
107 |
|
* </table> |
108 |
|
* |
94 |
– |
* <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is |
95 |
– |
* used for all parallel task execution in a program or subsystem. |
96 |
– |
* Otherwise, use would not usually outweigh the construction and |
97 |
– |
* bookkeeping overhead of creating a large set of threads. For |
98 |
– |
* example, a common pool could be used for the {@code SortTasks} |
99 |
– |
* illustrated in {@link RecursiveAction}. Because {@code |
100 |
– |
* ForkJoinPool} uses threads in {@linkplain java.lang.Thread#isDaemon |
101 |
– |
* daemon} mode, there is typically no need to explicitly {@link |
102 |
– |
* #shutdown} such a pool upon program exit. |
103 |
– |
* |
104 |
– |
* <pre> {@code |
105 |
– |
* static final ForkJoinPool mainPool = new ForkJoinPool(); |
106 |
– |
* ... |
107 |
– |
* public void sort(long[] array) { |
108 |
– |
* mainPool.invoke(new SortTask(array, 0, array.length)); |
109 |
– |
* }}</pre> |
110 |
– |
* |
109 |
|
* <p><b>Implementation notes</b>: This implementation restricts the |
110 |
|
* maximum number of running threads to 32767. Attempts to create |
111 |
|
* pools with greater than the maximum number result in |
123 |
|
/* |
124 |
|
* Implementation Overview |
125 |
|
* |
126 |
< |
* This class provides the central bookkeeping and control for a |
127 |
< |
* set of worker threads: Submissions from non-FJ threads enter |
128 |
< |
* into a submission queue. Workers take these tasks and typically |
129 |
< |
* split them into subtasks that may be stolen by other workers. |
130 |
< |
* Preference rules give first priority to processing tasks from |
131 |
< |
* their own queues (LIFO or FIFO, depending on mode), then to |
132 |
< |
* randomized FIFO steals of tasks in other worker queues, and |
133 |
< |
* lastly to new submissions. |
126 |
> |
* This class and its nested classes provide the main |
127 |
> |
* functionality and control for a set of worker threads: |
128 |
> |
* Submissions from non-FJ threads enter into submission queues. |
129 |
> |
* Workers take these tasks and typically split them into subtasks |
130 |
> |
* that may be stolen by other workers. Preference rules give |
131 |
> |
* first priority to processing tasks from their own queues (LIFO |
132 |
> |
* or FIFO, depending on mode), then to randomized FIFO steals of |
133 |
> |
* tasks in other queues. |
134 |
> |
* |
135 |
> |
* WorkQueues |
136 |
> |
* ========== |
137 |
> |
* |
138 |
> |
* Most operations occur within work-stealing queues (in nested |
139 |
> |
* class WorkQueue). These are special forms of Deques that |
140 |
> |
* support only three of the four possible end-operations -- push, |
141 |
> |
* pop, and poll (aka steal), under the further constraints that |
142 |
> |
* push and pop are called only from the owning thread (or, as |
143 |
> |
* extended here, under a lock), while poll may be called from |
144 |
> |
* other threads. (If you are unfamiliar with them, you probably |
145 |
> |
* want to read Herlihy and Shavit's book "The Art of |
146 |
> |
* Multiprocessor programming", chapter 16 describing these in |
147 |
> |
* more detail before proceeding.) The main work-stealing queue |
148 |
> |
* design is roughly similar to those in the papers "Dynamic |
149 |
> |
* Circular Work-Stealing Deque" by Chase and Lev, SPAA 2005 |
150 |
> |
* (http://research.sun.com/scalable/pubs/index.html) and |
151 |
> |
* "Idempotent work stealing" by Michael, Saraswat, and Vechev, |
152 |
> |
* PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186). |
153 |
> |
* The main differences ultimately stem from GC requirements that |
154 |
> |
* we null out taken slots as soon as we can, to maintain as small |
155 |
> |
* a footprint as possible even in programs generating huge |
156 |
> |
* numbers of tasks. To accomplish this, we shift the CAS |
157 |
> |
* arbitrating pop vs poll (steal) from being on the indices |
158 |
> |
* ("base" and "top") to the slots themselves. So, both a |
159 |
> |
* successful pop and poll mainly entail a CAS of a slot from |
160 |
> |
* non-null to null. Because we rely on CASes of references, we |
161 |
> |
* do not need tag bits on base or top. They are simple ints as |
162 |
> |
* used in any circular array-based queue (see for example |
163 |
> |
* ArrayDeque). Updates to the indices must still be ordered in a |
164 |
> |
* way that guarantees that top == base means the queue is empty, |
165 |
> |
* but otherwise may err on the side of possibly making the queue |
166 |
> |
* appear nonempty when a push, pop, or poll have not fully |
167 |
> |
* committed. Note that this means that the poll operation, |
168 |
> |
* considered individually, is not wait-free. One thief cannot |
169 |
> |
* successfully continue until another in-progress one (or, if |
170 |
> |
* previously empty, a push) completes. However, in the |
171 |
> |
* aggregate, we ensure at least probabilistic non-blockingness. |
172 |
> |
* If an attempted steal fails, a thief always chooses a different |
173 |
> |
* random victim target to try next. So, in order for one thief to |
174 |
> |
* progress, it suffices for any in-progress poll or new push on |
175 |
> |
* any empty queue to complete. (This is why we normally use |
176 |
> |
* method pollAt and its variants that try once at the apparent |
177 |
> |
* base index, else consider alternative actions, rather than |
178 |
> |
* method poll.) |
179 |
> |
* |
180 |
> |
* This approach also enables support of a user mode in which local |
181 |
> |
* task processing is in FIFO, not LIFO order, simply by using |
182 |
> |
* poll rather than pop. This can be useful in message-passing |
183 |
> |
* frameworks in which tasks are never joined. However neither |
184 |
> |
* mode considers affinities, loads, cache localities, etc, so |
185 |
> |
* rarely provide the best possible performance on a given |
186 |
> |
* machine, but portably provide good throughput by averaging over |
187 |
> |
* these factors. (Further, even if we did try to use such |
188 |
> |
* information, we do not usually have a basis for exploiting it. |
189 |
> |
* For example, some sets of tasks profit from cache affinities, |
190 |
> |
* but others are harmed by cache pollution effects.) |
191 |
> |
* |
192 |
> |
* WorkQueues are also used in a similar way for tasks submitted |
193 |
> |
* to the pool. We cannot mix these tasks in the same queues used |
194 |
> |
* for work-stealing (this would contaminate lifo/fifo |
195 |
> |
* processing). Instead, we loosely associate submission queues |
196 |
> |
* with submitting threads, using a form of hashing. The |
197 |
> |
* ThreadLocal Submitter class contains a value initially used as |
198 |
> |
* a hash code for choosing existing queues, but may be randomly |
199 |
> |
* repositioned upon contention with other submitters. In |
200 |
> |
* essence, submitters act like workers except that they never |
201 |
> |
* take tasks, and they are multiplexed on to a finite number of |
202 |
> |
* shared work queues. However, classes are set up so that future |
203 |
> |
* extensions could allow submitters to optionally help perform |
204 |
> |
* tasks as well. Insertion of tasks in shared mode requires a |
205 |
> |
* lock (mainly to protect in the case of resizing) but we use |
206 |
> |
* only a simple spinlock (using bits in field runState), because |
207 |
> |
* submitters encountering a busy queue move on to try or create |
208 |
> |
* other queues -- they block only when creating and registering |
209 |
> |
* new queues. |
210 |
> |
* |
211 |
> |
* Management |
212 |
> |
* ========== |
213 |
|
* |
214 |
|
* The main throughput advantages of work-stealing stem from |
215 |
|
* decentralized control -- workers mostly take tasks from |
216 |
|
* themselves or each other. We cannot negate this in the |
217 |
|
* implementation of other management responsibilities. The main |
218 |
|
* tactic for avoiding bottlenecks is packing nearly all |
219 |
< |
* essentially atomic control state into a single 64bit volatile |
220 |
< |
* variable ("ctl"). This variable is read on the order of 10-100 |
221 |
< |
* times as often as it is modified (always via CAS). (There is |
222 |
< |
* some additional control state, for example variable "shutdown" |
223 |
< |
* for which we can cope with uncoordinated updates.) This |
224 |
< |
* streamlines synchronization and control at the expense of messy |
225 |
< |
* constructions needed to repack status bits upon updates. |
226 |
< |
* Updates tend not to contend with each other except during |
227 |
< |
* bursts while submitted tasks begin or end. In some cases when |
228 |
< |
* they do contend, threads can instead do something else |
229 |
< |
* (usually, scan for tasks) until contention subsides. |
230 |
< |
* |
231 |
< |
* To enable packing, we restrict maximum parallelism to (1<<15)-1 |
232 |
< |
* (which is far in excess of normal operating range) to allow |
233 |
< |
* ids, counts, and their negations (used for thresholding) to fit |
234 |
< |
* into 16bit fields. |
235 |
< |
* |
236 |
< |
* Recording Workers. Workers are recorded in the "workers" array |
237 |
< |
* that is created upon pool construction and expanded if (rarely) |
238 |
< |
* necessary. This is an array as opposed to some other data |
239 |
< |
* structure to support index-based random steals by workers. |
240 |
< |
* Updates to the array recording new workers and unrecording |
241 |
< |
* terminated ones are protected from each other by a seqLock |
242 |
< |
* (scanGuard) but the array is otherwise concurrently readable, |
243 |
< |
* and accessed directly by workers. To simplify index-based |
244 |
< |
* operations, the array size is always a power of two, and all |
245 |
< |
* readers must tolerate null slots. To avoid flailing during |
246 |
< |
* start-up, the array is presized to hold twice #parallelism |
247 |
< |
* workers (which is unlikely to need further resizing during |
248 |
< |
* execution). But to avoid dealing with so many null slots, |
249 |
< |
* variable scanGuard includes a mask for the nearest power of two |
250 |
< |
* that contains all current workers. All worker thread creation |
251 |
< |
* is on-demand, triggered by task submissions, replacement of |
252 |
< |
* terminated workers, and/or compensation for blocked |
253 |
< |
* workers. However, all other support code is set up to work with |
254 |
< |
* other policies. To ensure that we do not hold on to worker |
255 |
< |
* references that would prevent GC, ALL accesses to workers are |
256 |
< |
* via indices into the workers array (which is one source of some |
257 |
< |
* of the messy code constructions here). In essence, the workers |
258 |
< |
* array serves as a weak reference mechanism. Thus for example |
259 |
< |
* the wait queue field of ctl stores worker indices, not worker |
260 |
< |
* references. Access to the workers in associated methods (for |
261 |
< |
* example signalWork) must both index-check and null-check the |
262 |
< |
* IDs. All such accesses ignore bad IDs by returning out early |
263 |
< |
* from what they are doing, since this can only be associated |
264 |
< |
* with termination, in which case it is OK to give up. |
265 |
< |
* |
266 |
< |
* All uses of the workers array, as well as queue arrays, check |
267 |
< |
* that the array is non-null (even if previously non-null). This |
268 |
< |
* allows nulling during termination, which is currently not |
192 |
< |
* necessary, but remains an option for resource-revocation-based |
193 |
< |
* shutdown schemes. |
219 |
> |
* essentially atomic control state into two volatile variables |
220 |
> |
* that are by far most often read (not written) as status and |
221 |
> |
* consistency checks. |
222 |
> |
* |
223 |
> |
* Field "ctl" contains 64 bits holding all the information needed |
224 |
> |
* to atomically decide to add, inactivate, enqueue (on an event |
225 |
> |
* queue), dequeue, and/or re-activate workers. To enable this |
226 |
> |
* packing, we restrict maximum parallelism to (1<<15)-1 (which is |
227 |
> |
* far in excess of normal operating range) to allow ids, counts, |
228 |
> |
* and their negations (used for thresholding) to fit into 16bit |
229 |
> |
* fields. |
230 |
> |
* |
231 |
> |
* Field "runState" contains 32 bits needed to register and |
232 |
> |
* deregister WorkQueues, as well as to enable shutdown. It is |
233 |
> |
* only modified under a lock (normally briefly held, but |
234 |
> |
* occasionally protecting allocations and resizings) but even |
235 |
> |
* when locked remains available to check consistency. |
236 |
> |
* |
237 |
> |
* Recording WorkQueues. WorkQueues are recorded in the |
238 |
> |
* "workQueues" array that is created upon first use and expanded |
239 |
> |
* if necessary. Updates to the array while recording new workers |
240 |
> |
* and unrecording terminated ones are protected from each other |
241 |
> |
* by a lock but the array is otherwise concurrently readable, and |
242 |
> |
* accessed directly. To simplify index-based operations, the |
243 |
> |
* array size is always a power of two, and all readers must |
244 |
> |
* tolerate null slots. Shared (submission) queues are at even |
245 |
> |
* indices, worker queues at odd indices. Grouping them together |
246 |
> |
* in this way simplifies and speeds up task scanning. |
247 |
> |
* |
248 |
> |
* All worker thread creation is on-demand, triggered by task |
249 |
> |
* submissions, replacement of terminated workers, and/or |
250 |
> |
* compensation for blocked workers. However, all other support |
251 |
> |
* code is set up to work with other policies. To ensure that we |
252 |
> |
* do not hold on to worker references that would prevent GC, ALL |
253 |
> |
* accesses to workQueues are via indices into the workQueues |
254 |
> |
* array (which is one source of some of the messy code |
255 |
> |
* constructions here). In essence, the workQueues array serves as |
256 |
> |
* a weak reference mechanism. Thus for example the wait queue |
257 |
> |
* field of ctl stores indices, not references. Access to the |
258 |
> |
* workQueues in associated methods (for example signalWork) must |
259 |
> |
* both index-check and null-check the IDs. All such accesses |
260 |
> |
* ignore bad IDs by returning out early from what they are doing, |
261 |
> |
* since this can only be associated with termination, in which |
262 |
> |
* case it is OK to give up. All uses of the workQueues array |
263 |
> |
* also check that it is non-null (even if previously |
264 |
> |
* non-null). This allows nulling during termination, which is |
265 |
> |
* currently not necessary, but remains an option for |
266 |
> |
* resource-revocation-based shutdown schemes. It also helps |
267 |
> |
* reduce JIT issuance of uncommon-trap code, which tends to |
268 |
> |
* unnecessarily complicate control flow in some methods. |
269 |
|
* |
270 |
< |
* Wait Queuing. Unlike HPC work-stealing frameworks, we cannot |
270 |
> |
* Event Queuing. Unlike HPC work-stealing frameworks, we cannot |
271 |
|
* let workers spin indefinitely scanning for tasks when none can |
272 |
|
* be found immediately, and we cannot start/resume workers unless |
273 |
|
* there appear to be tasks available. On the other hand, we must |
274 |
|
* quickly prod them into action when new tasks are submitted or |
275 |
< |
* generated. We park/unpark workers after placing in an event |
276 |
< |
* wait queue when they cannot find work. This "queue" is actually |
277 |
< |
* a simple Treiber stack, headed by the "id" field of ctl, plus a |
278 |
< |
* 15bit counter value to both wake up waiters (by advancing their |
279 |
< |
* count) and avoid ABA effects. Successors are held in worker |
280 |
< |
* field "nextWait". Queuing deals with several intrinsic races, |
281 |
< |
* mainly that a task-producing thread can miss seeing (and |
275 |
> |
* generated. In many usages, ramp-up time to activate workers is |
276 |
> |
* the main limiting factor in overall performance (this is |
277 |
> |
* compounded at program start-up by JIT compilation and |
278 |
> |
* allocation). So we try to streamline this as much as possible. |
279 |
> |
* We park/unpark workers after placing in an event wait queue |
280 |
> |
* when they cannot find work. This "queue" is actually a simple |
281 |
> |
* Treiber stack, headed by the "id" field of ctl, plus a 15bit |
282 |
> |
* counter value (that reflects the number of times a worker has |
283 |
> |
* been inactivated) to avoid ABA effects (we need only as many |
284 |
> |
* version numbers as worker threads). Successors are held in |
285 |
> |
* field WorkQueue.nextWait. Queuing deals with several intrinsic |
286 |
> |
* races, mainly that a task-producing thread can miss seeing (and |
287 |
|
* signalling) another thread that gave up looking for work but |
288 |
|
* has not yet entered the wait queue. We solve this by requiring |
289 |
< |
* a full sweep of all workers both before (in scan()) and after |
290 |
< |
* (in tryAwaitWork()) a newly waiting worker is added to the wait |
291 |
< |
* queue. During a rescan, the worker might release some other |
292 |
< |
* queued worker rather than itself, which has the same net |
293 |
< |
* effect. Because enqueued workers may actually be rescanning |
294 |
< |
* rather than waiting, we set and clear the "parked" field of |
295 |
< |
* ForkJoinWorkerThread to reduce unnecessary calls to unpark. |
296 |
< |
* (Use of the parked field requires a secondary recheck to avoid |
297 |
< |
* missed signals.) |
289 |
> |
* a full sweep of all workers (via repeated calls to method |
290 |
> |
* scan()) both before and after a newly waiting worker is added |
291 |
> |
* to the wait queue. During a rescan, the worker might release |
292 |
> |
* some other queued worker rather than itself, which has the same |
293 |
> |
* net effect. Because enqueued workers may actually be rescanning |
294 |
> |
* rather than waiting, we set and clear the "parker" field of |
295 |
> |
* WorkQueues to reduce unnecessary calls to unpark. (This |
296 |
> |
* requires a secondary recheck to avoid missed signals.) Note |
297 |
> |
* the unusual conventions about Thread.interrupts surrounding |
298 |
> |
* parking and other blocking: Because interrupts are used solely |
299 |
> |
* to alert threads to check termination, which is checked anyway |
300 |
> |
* upon blocking, we clear status (using Thread.interrupted) |
301 |
> |
* before any call to park, so that park does not immediately |
302 |
> |
* return due to status being set via some other unrelated call to |
303 |
> |
* interrupt in user code. |
304 |
|
* |
305 |
|
* Signalling. We create or wake up workers only when there |
306 |
|
* appears to be at least one task they might be able to find and |
307 |
|
* execute. When a submission is added or another worker adds a |
308 |
< |
* task to a queue that previously had two or fewer tasks, they |
308 |
> |
* task to a queue that previously had fewer than two tasks, they |
309 |
|
* signal waiting workers (or trigger creation of new ones if |
310 |
|
* fewer than the given parallelism level -- see signalWork). |
311 |
< |
* These primary signals are buttressed by signals during rescans |
312 |
< |
* as well as those performed when a worker steals a task and |
313 |
< |
* notices that there are more tasks too; together these cover the |
314 |
< |
* signals needed in cases when more than two tasks are pushed |
229 |
< |
* but untaken. |
311 |
> |
* These primary signals are buttressed by signals during rescans; |
312 |
> |
* together these cover the signals needed in cases when more |
313 |
> |
* tasks are pushed but untaken, and improve performance compared |
314 |
> |
* to having one thread wake up all workers. |
315 |
|
* |
316 |
|
* Trimming workers. To release resources after periods of lack of |
317 |
|
* use, a worker starting to wait when the pool is quiescent will |
318 |
< |
* time out and terminate if the pool has remained quiescent for |
319 |
< |
* SHRINK_RATE nanosecs. This will slowly propagate, eventually |
320 |
< |
* terminating all workers after long periods of non-use. |
321 |
< |
* |
322 |
< |
* Submissions. External submissions are maintained in an |
323 |
< |
* array-based queue that is structured identically to |
324 |
< |
* ForkJoinWorkerThread queues except for the use of |
325 |
< |
* submissionLock in method addSubmission. Unlike the case for |
326 |
< |
* worker queues, multiple external threads can add new |
327 |
< |
* submissions, so adding requires a lock. |
328 |
< |
* |
329 |
< |
* Compensation. Beyond work-stealing support and lifecycle |
330 |
< |
* control, the main responsibility of this framework is to take |
331 |
< |
* actions when one worker is waiting to join a task stolen (or |
332 |
< |
* always held by) another. Because we are multiplexing many |
333 |
< |
* tasks on to a pool of workers, we can't just let them block (as |
334 |
< |
* in Thread.join). We also cannot just reassign the joiner's |
335 |
< |
* run-time stack with another and replace it later, which would |
336 |
< |
* be a form of "continuation", that even if possible is not |
337 |
< |
* necessarily a good idea since we sometimes need both an |
338 |
< |
* unblocked task and its continuation to progress. Instead we |
339 |
< |
* combine two tactics: |
318 |
> |
* time out and terminate if the pool has remained quiescent for a |
319 |
> |
* given period -- a short period if there are more threads than |
320 |
> |
* parallelism, longer as the number of threads decreases. This |
321 |
> |
* will slowly propagate, eventually terminating all workers after |
322 |
> |
* periods of non-use. |
323 |
> |
* |
324 |
> |
* Shutdown and Termination. A call to shutdownNow atomically sets |
325 |
> |
* a runState bit and then (non-atomically) sets each worker's |
326 |
> |
* runState status, cancels all unprocessed tasks, and wakes up |
327 |
> |
* all waiting workers. Detecting whether termination should |
328 |
> |
* commence after a non-abrupt shutdown() call requires more work |
329 |
> |
* and bookkeeping. We need consensus about quiescence (i.e., that |
330 |
> |
* there is no more work). The active count provides a primary |
331 |
> |
* indication but non-abrupt shutdown still requires a rechecking |
332 |
> |
* scan for any workers that are inactive but not queued. |
333 |
> |
* |
334 |
> |
* Joining Tasks |
335 |
> |
* ============= |
336 |
> |
* |
337 |
> |
* Any of several actions may be taken when one worker is waiting |
338 |
> |
* to join a task stolen (or always held) by another. Because we |
339 |
> |
* are multiplexing many tasks on to a pool of workers, we can't |
340 |
> |
* just let them block (as in Thread.join). We also cannot just |
341 |
> |
* reassign the joiner's run-time stack with another and replace |
342 |
> |
* it later, which would be a form of "continuation", that even if |
343 |
> |
* possible is not necessarily a good idea since we sometimes need |
344 |
> |
* both an unblocked task and its continuation to progress. |
345 |
> |
* Instead we combine two tactics: |
346 |
|
* |
347 |
|
* Helping: Arranging for the joiner to execute some task that it |
348 |
< |
* would be running if the steal had not occurred. Method |
258 |
< |
* ForkJoinWorkerThread.joinTask tracks joining->stealing |
259 |
< |
* links to try to find such a task. |
348 |
> |
* would be running if the steal had not occurred. |
349 |
|
* |
350 |
|
* Compensating: Unless there are already enough live threads, |
351 |
< |
* method tryPreBlock() may create or re-activate a spare |
352 |
< |
* thread to compensate for blocked joiners until they |
353 |
< |
* unblock. |
351 |
> |
* method tryCompensate() may create or re-activate a spare |
352 |
> |
* thread to compensate for blocked joiners until they unblock. |
353 |
> |
* |
354 |
> |
* A third form (implemented in tryRemoveAndExec and |
355 |
> |
* tryPollForAndExec) amounts to helping a hypothetical |
356 |
> |
* compensator: If we can readily tell that a possible action of a |
357 |
> |
* compensator is to steal and execute the task being joined, the |
358 |
> |
* joining thread can do so directly, without the need for a |
359 |
> |
* compensation thread (although at the expense of larger run-time |
360 |
> |
* stacks, but the tradeoff is typically worthwhile). |
361 |
|
* |
362 |
|
* The ManagedBlocker extension API can't use helping so relies |
363 |
|
* only on compensation in method awaitBlocker. |
364 |
|
* |
365 |
+ |
* The algorithm in tryHelpStealer entails a form of "linear" |
366 |
+ |
* helping: Each worker records (in field currentSteal) the most |
367 |
+ |
* recent task it stole from some other worker. Plus, it records |
368 |
+ |
* (in field currentJoin) the task it is currently actively |
369 |
+ |
* joining. Method tryHelpStealer uses these markers to try to |
370 |
+ |
* find a worker to help (i.e., steal back a task from and execute |
371 |
+ |
* it) that could hasten completion of the actively joined task. |
372 |
+ |
* In essence, the joiner executes a task that would be on its own |
373 |
+ |
* local deque had the to-be-joined task not been stolen. This may |
374 |
+ |
* be seen as a conservative variant of the approach in Wagner & |
375 |
+ |
* Calder "Leapfrogging: a portable technique for implementing |
376 |
+ |
* efficient futures" SIGPLAN Notices, 1993 |
377 |
+ |
* (http://portal.acm.org/citation.cfm?id=155354). It differs in |
378 |
+ |
* that: (1) We only maintain dependency links across workers upon |
379 |
+ |
* steals, rather than use per-task bookkeeping. This sometimes |
380 |
+ |
* requires a linear scan of workQueues array to locate stealers, |
381 |
+ |
* but often doesn't because stealers leave hints (that may become |
382 |
+ |
* stale/wrong) of where to locate them. A stealHint is only a |
383 |
+ |
* hint because a worker might have had multiple steals and the |
384 |
+ |
* hint records only one of them (usually the most current). |
385 |
+ |
* Hinting isolates cost to when it is needed, rather than adding |
386 |
+ |
* to per-task overhead. (2) It is "shallow", ignoring nesting |
387 |
+ |
* and potentially cyclic mutual steals. (3) It is intentionally |
388 |
+ |
* racy: field currentJoin is updated only while actively joining, |
389 |
+ |
* which means that we miss links in the chain during long-lived |
390 |
+ |
* tasks, GC stalls etc (which is OK since blocking in such cases |
391 |
+ |
* is usually a good idea). (4) We bound the number of attempts |
392 |
+ |
* to find work (see MAX_HELP) and fall back to suspending the |
393 |
+ |
* worker and if necessary replacing it with another. |
394 |
+ |
* |
395 |
|
* It is impossible to keep exactly the target parallelism number |
396 |
|
* of threads running at any given time. Determining the |
397 |
|
* existence of conservatively safe helping targets, the |
398 |
|
* availability of already-created spares, and the apparent need |
399 |
< |
* to create new spares are all racy and require heuristic |
400 |
< |
* guidance, so we rely on multiple retries of each. Currently, |
401 |
< |
* in keeping with on-demand signalling policy, we compensate only |
402 |
< |
* if blocking would leave less than one active (non-waiting, |
403 |
< |
* non-blocked) worker. Additionally, to avoid some false alarms |
404 |
< |
* due to GC, lagging counters, system activity, etc, compensated |
405 |
< |
* blocking for joins is only attempted after rechecks stabilize |
406 |
< |
* (retries are interspersed with Thread.yield, for good |
407 |
< |
* citizenship). The variable blockedCount, incremented before |
408 |
< |
* blocking and decremented after, is sometimes needed to |
409 |
< |
* distinguish cases of waiting for work vs blocking on joins or |
410 |
< |
* other managed sync. Both cases are equivalent for most pool |
411 |
< |
* control, so we can update non-atomically. (Additionally, |
412 |
< |
* contention on blockedCount alleviates some contention on ctl). |
413 |
< |
* |
414 |
< |
* Shutdown and Termination. A call to shutdownNow atomically sets |
415 |
< |
* the ctl stop bit and then (non-atomically) sets each workers |
416 |
< |
* "terminate" status, cancels all unprocessed tasks, and wakes up |
417 |
< |
* all waiting workers. Detecting whether termination should |
418 |
< |
* commence after a non-abrupt shutdown() call requires more work |
419 |
< |
* and bookkeeping. We need consensus about quiescence (i.e., that |
420 |
< |
* there is no more work) which is reflected in active counts so |
421 |
< |
* long as there are no current blockers, as well as possible |
422 |
< |
* re-evaluations during independent changes in blocking or |
423 |
< |
* quiescing workers. |
399 |
> |
* to create new spares are all racy, so we rely on multiple |
400 |
> |
* retries of each. Compensation in the apparent absence of |
401 |
> |
* helping opportunities is challenging to control on JVMs, where |
402 |
> |
* GC and other activities can stall progress of tasks that in |
403 |
> |
* turn stall out many other dependent tasks, without us being |
404 |
> |
* able to determine whether they will ever require compensation. |
405 |
> |
* Even though work-stealing otherwise encounters little |
406 |
> |
* degradation in the presence of more threads than cores, |
407 |
> |
* aggressively adding new threads in such cases entails risk of |
408 |
> |
* unwanted positive feedback control loops in which more threads |
409 |
> |
* cause more dependent stalls (as well as delayed progress of |
410 |
> |
* unblocked threads to the point that we know they are available) |
411 |
> |
* leading to more situations requiring more threads, and so |
412 |
> |
* on. This aspect of control can be seen as an (analytically |
413 |
> |
* intractable) game with an opponent that may choose the worst |
414 |
> |
* (for us) active thread to stall at any time. We take several |
415 |
> |
* precautions to bound losses (and thus bound gains), mainly in |
416 |
> |
* methods tryCompensate and awaitJoin: (1) We only try |
417 |
> |
* compensation after attempting enough helping steps (measured |
418 |
> |
* via counting and timing) that we have already consumed the |
419 |
> |
* estimated cost of creating and activating a new thread. (2) We |
420 |
> |
* allow up to 50% of threads to be blocked before initially |
421 |
> |
* adding any others, and unless completely saturated, check that |
422 |
> |
* some work is available for a new worker before adding. Also, we |
423 |
> |
* create up to only 50% more threads until entering a mode that |
424 |
> |
* only adds a thread if all others are possibly blocked. All |
425 |
> |
* together, this means that we might be half as fast to react, |
426 |
> |
* and create half as many threads as possible in the ideal case, |
427 |
> |
* but present vastly fewer anomalies in all other cases compared |
428 |
> |
* to both more aggressive and more conservative alternatives. |
429 |
|
* |
430 |
|
* Style notes: There is a lot of representation-level coupling |
431 |
|
* among classes ForkJoinPool, ForkJoinWorkerThread, and |
432 |
< |
* ForkJoinTask. Most fields of ForkJoinWorkerThread maintain |
433 |
< |
* data structures managed by ForkJoinPool, so are directly |
434 |
< |
* accessed. Conversely we allow 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. All together, these low-level implementation |
440 |
< |
* choices produce as much as a factor of 4 performance |
441 |
< |
* improvement compared to naive implementations, and enable the |
442 |
< |
* processing of billions of tasks per second, at the expense of |
443 |
< |
* some ugliness. |
444 |
< |
* |
445 |
< |
* Methods signalWork() and scan() are the main bottlenecks so are |
446 |
< |
* especially heavily micro-optimized/mangled. There are lots of |
447 |
< |
* inline assignments (of form "while ((local = field) != 0)") |
448 |
< |
* which are usually the simplest way to ensure the required read |
449 |
< |
* orderings (which are sometimes critical). This leads to a |
450 |
< |
* "C"-like style of listing declarations of these locals at the |
451 |
< |
* heads of methods or blocks. There are several occurrences of |
452 |
< |
* the unusual "do {} while (!cas...)" which is the simplest way |
453 |
< |
* to force an update of a CAS'ed variable. There are also other |
454 |
< |
* coding oddities that help some methods perform reasonably even |
455 |
< |
* when interpreted (not compiled). |
456 |
< |
* |
457 |
< |
* The order of declarations in this file is: (1) declarations of |
458 |
< |
* statics (2) fields (along with constants used when unpacking |
459 |
< |
* some of them), listed in an order that tends to reduce |
460 |
< |
* contention among them a bit under most JVMs. (3) internal |
461 |
< |
* control methods (4) callbacks and other support for |
462 |
< |
* ForkJoinTask and ForkJoinWorkerThread classes, (5) exported |
463 |
< |
* methods (plus a few little helpers). (6) static block |
464 |
< |
* initializing all statics in a minimally dependent order. |
432 |
> |
* ForkJoinTask. The fields of WorkQueue maintain data structures |
433 |
> |
* managed by ForkJoinPool, so are directly accessed. There is |
434 |
> |
* little point trying to reduce this, since any associated future |
435 |
> |
* changes in representations will need to be accompanied by |
436 |
> |
* algorithmic changes anyway. Several methods intrinsically |
437 |
> |
* sprawl because they must accumulate sets of consistent reads of |
438 |
> |
* volatiles held in local variables. Methods signalWork() and |
439 |
> |
* scan() are the main bottlenecks, so are especially heavily |
440 |
> |
* micro-optimized/mangled. There are lots of inline assignments |
441 |
> |
* (of form "while ((local = field) != 0)") which are usually the |
442 |
> |
* simplest way to ensure the required read orderings (which are |
443 |
> |
* sometimes critical). This leads to a "C"-like style of listing |
444 |
> |
* declarations of these locals at the heads of methods or blocks. |
445 |
> |
* There are several occurrences of the unusual "do {} while |
446 |
> |
* (!cas...)" which is the simplest way to force an update of a |
447 |
> |
* CAS'ed variable. There are also other coding oddities that help |
448 |
> |
* some methods perform reasonably even when interpreted (not |
449 |
> |
* compiled). |
450 |
> |
* |
451 |
> |
* The order of declarations in this file is: |
452 |
> |
* (1) Static utility functions |
453 |
> |
* (2) Nested (static) classes |
454 |
> |
* (3) Static fields |
455 |
> |
* (4) Fields, along with constants used when unpacking some of them |
456 |
> |
* (5) Internal control methods |
457 |
> |
* (6) Callbacks and other support for ForkJoinTask methods |
458 |
> |
* (7) Exported methods |
459 |
> |
* (8) Static block initializing statics in minimally dependent order |
460 |
> |
*/ |
461 |
> |
|
462 |
> |
// Static utilities |
463 |
> |
|
464 |
> |
/** |
465 |
> |
* If there is a security manager, makes sure caller has |
466 |
> |
* permission to modify threads. |
467 |
|
*/ |
468 |
+ |
private static void checkPermission() { |
469 |
+ |
SecurityManager security = System.getSecurityManager(); |
470 |
+ |
if (security != null) |
471 |
+ |
security.checkPermission(modifyThreadPermission); |
472 |
+ |
} |
473 |
+ |
|
474 |
+ |
// Nested classes |
475 |
|
|
476 |
|
/** |
477 |
|
* Factory for creating new {@link ForkJoinWorkerThread}s. |
501 |
|
} |
502 |
|
|
503 |
|
/** |
504 |
< |
* Creates a new ForkJoinWorkerThread. This factory is used unless |
505 |
< |
* overridden in ForkJoinPool constructors. |
504 |
> |
* Class for artificial tasks that are used to replace the target |
505 |
> |
* of local joins if they are removed from an interior queue slot |
506 |
> |
* in WorkQueue.tryRemoveAndExec. We don't need the proxy to |
507 |
> |
* actually do anything beyond having a unique identity. |
508 |
> |
*/ |
509 |
> |
static final class EmptyTask extends ForkJoinTask<Void> { |
510 |
> |
EmptyTask() { status = ForkJoinTask.NORMAL; } // force done |
511 |
> |
public final Void getRawResult() { return null; } |
512 |
> |
public final void setRawResult(Void x) {} |
513 |
> |
public final boolean exec() { return true; } |
514 |
> |
} |
515 |
> |
|
516 |
> |
/** |
517 |
> |
* Queues supporting work-stealing as well as external task |
518 |
> |
* submission. See above for main rationale and algorithms. |
519 |
> |
* Implementation relies heavily on "Unsafe" intrinsics |
520 |
> |
* and selective use of "volatile": |
521 |
> |
* |
522 |
> |
* Field "base" is the index (mod array.length) of the least valid |
523 |
> |
* queue slot, which is always the next position to steal (poll) |
524 |
> |
* from if nonempty. Reads and writes require volatile orderings |
525 |
> |
* but not CAS, because updates are only performed after slot |
526 |
> |
* CASes. |
527 |
> |
* |
528 |
> |
* Field "top" is the index (mod array.length) of the next queue |
529 |
> |
* slot to push to or pop from. It is written only by owner thread |
530 |
> |
* for push, or under lock for trySharedPush, and accessed by |
531 |
> |
* other threads only after reading (volatile) base. Both top and |
532 |
> |
* base are allowed to wrap around on overflow, but (top - base) |
533 |
> |
* (or more commonly -(base - top) to force volatile read of base |
534 |
> |
* before top) still estimates size. |
535 |
> |
* |
536 |
> |
* The array slots are read and written using the emulation of |
537 |
> |
* volatiles/atomics provided by Unsafe. Insertions must in |
538 |
> |
* general use putOrderedObject as a form of releasing store to |
539 |
> |
* ensure that all writes to the task object are ordered before |
540 |
> |
* its publication in the queue. (Although we can avoid one case |
541 |
> |
* of this when locked in trySharedPush.) All removals entail a |
542 |
> |
* CAS to null. The array is always a power of two. To ensure |
543 |
> |
* safety of Unsafe array operations, all accesses perform |
544 |
> |
* explicit null checks and implicit bounds checks via |
545 |
> |
* power-of-two masking. |
546 |
> |
* |
547 |
> |
* In addition to basic queuing support, this class contains |
548 |
> |
* fields described elsewhere to control execution. It turns out |
549 |
> |
* to work better memory-layout-wise to include them in this |
550 |
> |
* class rather than a separate class. |
551 |
> |
* |
552 |
> |
* Performance on most platforms is very sensitive to placement of |
553 |
> |
* instances of both WorkQueues and their arrays -- we absolutely |
554 |
> |
* do not want multiple WorkQueue instances or multiple queue |
555 |
> |
* arrays sharing cache lines. (It would be best for queue objects |
556 |
> |
* and their arrays to share, but there is nothing available to |
557 |
> |
* help arrange that). Unfortunately, because they are recorded |
558 |
> |
* in a common array, WorkQueue instances are often moved to be |
559 |
> |
* adjacent by garbage collectors. To reduce impact, we use field |
560 |
> |
* padding that works OK on common platforms; this effectively |
561 |
> |
* trades off slightly slower average field access for the sake of |
562 |
> |
* avoiding really bad worst-case access. (Until better JVM |
563 |
> |
* support is in place, this padding is dependent on transient |
564 |
> |
* properties of JVM field layout rules.) We also take care in |
565 |
> |
* allocating, sizing and resizing the array. Non-shared queue |
566 |
> |
* arrays are initialized (via method growArray) by workers before |
567 |
> |
* use. Others are allocated on first use. |
568 |
|
*/ |
569 |
< |
public static final ForkJoinWorkerThreadFactory |
570 |
< |
defaultForkJoinWorkerThreadFactory; |
569 |
> |
static final class WorkQueue { |
570 |
> |
/** |
571 |
> |
* Capacity of work-stealing queue array upon initialization. |
572 |
> |
* Must be a power of two; at least 4, but should be larger to |
573 |
> |
* reduce or eliminate cacheline sharing among queues. |
574 |
> |
* Currently, it is much larger, as a partial workaround for |
575 |
> |
* the fact that JVMs often place arrays in locations that |
576 |
> |
* share GC bookkeeping (especially cardmarks) such that |
577 |
> |
* per-write accesses encounter serious memory contention. |
578 |
> |
*/ |
579 |
> |
static final int INITIAL_QUEUE_CAPACITY = 1 << 13; |
580 |
|
|
581 |
< |
/** |
582 |
< |
* Permission required for callers of methods that may start or |
583 |
< |
* kill threads. |
584 |
< |
*/ |
585 |
< |
private static final RuntimePermission modifyThreadPermission; |
581 |
> |
/** |
582 |
> |
* Maximum size for queue arrays. Must be a power of two less |
583 |
> |
* than or equal to 1 << (31 - width of array entry) to ensure |
584 |
> |
* lack of wraparound of index calculations, but defined to a |
585 |
> |
* value a bit less than this to help users trap runaway |
586 |
> |
* programs before saturating systems. |
587 |
> |
*/ |
588 |
> |
static final int MAXIMUM_QUEUE_CAPACITY = 1 << 26; // 64M |
589 |
> |
|
590 |
> |
volatile long totalSteals; // cumulative number of steals |
591 |
> |
int seed; // for random scanning; initialize nonzero |
592 |
> |
volatile int eventCount; // encoded inactivation count; < 0 if inactive |
593 |
> |
int nextWait; // encoded record of next event waiter |
594 |
> |
int rescans; // remaining scans until block |
595 |
> |
int nsteals; // top-level task executions since last idle |
596 |
> |
final int mode; // lifo, fifo, or shared |
597 |
> |
int poolIndex; // index of this queue in pool (or 0) |
598 |
> |
int stealHint; // index of most recent known stealer |
599 |
> |
volatile int runState; // 1: locked, -1: terminate; else 0 |
600 |
> |
volatile int base; // index of next slot for poll |
601 |
> |
int top; // index of next slot for push |
602 |
> |
ForkJoinTask<?>[] array; // the elements (initially unallocated) |
603 |
> |
final ForkJoinPool pool; // the containing pool (may be null) |
604 |
> |
final ForkJoinWorkerThread owner; // owning thread or null if shared |
605 |
> |
volatile Thread parker; // == owner during call to park; else null |
606 |
> |
volatile ForkJoinTask<?> currentJoin; // task being joined in awaitJoin |
607 |
> |
ForkJoinTask<?> currentSteal; // current non-local task being executed |
608 |
> |
// Heuristic padding to ameliorate unfortunate memory placements |
609 |
> |
Object p00, p01, p02, p03, p04, p05, p06, p07; |
610 |
> |
Object p08, p09, p0a, p0b, p0c, p0d, p0e; |
611 |
> |
|
612 |
> |
WorkQueue(ForkJoinPool pool, ForkJoinWorkerThread owner, int mode) { |
613 |
> |
this.mode = mode; |
614 |
> |
this.pool = pool; |
615 |
> |
this.owner = owner; |
616 |
> |
// Place indices in the center of array (that is not yet allocated) |
617 |
> |
base = top = INITIAL_QUEUE_CAPACITY >>> 1; |
618 |
> |
} |
619 |
> |
|
620 |
> |
/** |
621 |
> |
* Returns the approximate number of tasks in the queue. |
622 |
> |
*/ |
623 |
> |
final int queueSize() { |
624 |
> |
int n = base - top; // non-owner callers must read base first |
625 |
> |
return (n >= 0) ? 0 : -n; // ignore transient negative |
626 |
> |
} |
627 |
> |
|
628 |
> |
/** |
629 |
> |
* Provides a more accurate estimate of whether this queue has |
630 |
> |
* any tasks than does queueSize, by checking whether a |
631 |
> |
* near-empty queue has at least one unclaimed task. |
632 |
> |
*/ |
633 |
> |
final boolean isEmpty() { |
634 |
> |
ForkJoinTask<?>[] a; int m, s; |
635 |
> |
int n = base - (s = top); |
636 |
> |
return (n >= 0 || |
637 |
> |
(n == -1 && |
638 |
> |
((a = array) == null || |
639 |
> |
(m = a.length - 1) < 0 || |
640 |
> |
U.getObjectVolatile |
641 |
> |
(a, ((m & (s - 1)) << ASHIFT) + ABASE) == null))); |
642 |
> |
} |
643 |
> |
|
644 |
> |
/** |
645 |
> |
* Pushes a task. Call only by owner in unshared queues. |
646 |
> |
* |
647 |
> |
* @param task the task. Caller must ensure non-null. |
648 |
> |
* @throw RejectedExecutionException if array cannot be resized |
649 |
> |
*/ |
650 |
> |
final void push(ForkJoinTask<?> task) { |
651 |
> |
ForkJoinTask<?>[] a; ForkJoinPool p; |
652 |
> |
int s = top, m, n; |
653 |
> |
if ((a = array) != null) { // ignore if queue removed |
654 |
> |
U.putOrderedObject |
655 |
> |
(a, (((m = a.length - 1) & s) << ASHIFT) + ABASE, task); |
656 |
> |
if ((n = (top = s + 1) - base) <= 2) { |
657 |
> |
if ((p = pool) != null) |
658 |
> |
p.signalWork(); |
659 |
> |
} |
660 |
> |
else if (n >= m) |
661 |
> |
growArray(true); |
662 |
> |
} |
663 |
> |
} |
664 |
> |
|
665 |
> |
/** |
666 |
> |
* Pushes a task if lock is free and array is either big |
667 |
> |
* enough or can be resized to be big enough. |
668 |
> |
* |
669 |
> |
* @param task the task. Caller must ensure non-null. |
670 |
> |
* @return true if submitted |
671 |
> |
*/ |
672 |
> |
final boolean trySharedPush(ForkJoinTask<?> task) { |
673 |
> |
boolean submitted = false; |
674 |
> |
if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) { |
675 |
> |
ForkJoinTask<?>[] a = array; |
676 |
> |
int s = top; |
677 |
> |
try { |
678 |
> |
if ((a != null && a.length > s + 1 - base) || |
679 |
> |
(a = growArray(false)) != null) { // must presize |
680 |
> |
int j = (((a.length - 1) & s) << ASHIFT) + ABASE; |
681 |
> |
U.putObject(a, (long)j, task); // don't need "ordered" |
682 |
> |
top = s + 1; |
683 |
> |
submitted = true; |
684 |
> |
} |
685 |
> |
} finally { |
686 |
> |
runState = 0; // unlock |
687 |
> |
} |
688 |
> |
} |
689 |
> |
return submitted; |
690 |
> |
} |
691 |
> |
|
692 |
> |
/** |
693 |
> |
* Takes next task, if one exists, in LIFO order. Call only |
694 |
> |
* by owner in unshared queues. |
695 |
> |
*/ |
696 |
> |
final ForkJoinTask<?> pop() { |
697 |
> |
ForkJoinTask<?>[] a; ForkJoinTask<?> t; int m; |
698 |
> |
if ((a = array) != null && (m = a.length - 1) >= 0) { |
699 |
> |
for (int s; (s = top - 1) - base >= 0;) { |
700 |
> |
long j = ((m & s) << ASHIFT) + ABASE; |
701 |
> |
if ((t = (ForkJoinTask<?>)U.getObject(a, j)) == null) |
702 |
> |
break; |
703 |
> |
if (U.compareAndSwapObject(a, j, t, null)) { |
704 |
> |
top = s; |
705 |
> |
return t; |
706 |
> |
} |
707 |
> |
} |
708 |
> |
} |
709 |
> |
return null; |
710 |
> |
} |
711 |
> |
|
712 |
> |
final ForkJoinTask<?> sharedPop() { |
713 |
> |
ForkJoinTask<?> task = null; |
714 |
> |
if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) { |
715 |
> |
try { |
716 |
> |
ForkJoinTask<?>[] a; int m; |
717 |
> |
if ((a = array) != null && (m = a.length - 1) >= 0) { |
718 |
> |
for (int s; (s = top - 1) - base >= 0;) { |
719 |
> |
long j = ((m & s) << ASHIFT) + ABASE; |
720 |
> |
ForkJoinTask<?> t = |
721 |
> |
(ForkJoinTask<?>)U.getObject(a, j); |
722 |
> |
if (t == null) |
723 |
> |
break; |
724 |
> |
if (U.compareAndSwapObject(a, j, t, null)) { |
725 |
> |
top = s; |
726 |
> |
task = t; |
727 |
> |
break; |
728 |
> |
} |
729 |
> |
} |
730 |
> |
} |
731 |
> |
} finally { |
732 |
> |
runState = 0; |
733 |
> |
} |
734 |
> |
} |
735 |
> |
return task; |
736 |
> |
} |
737 |
> |
|
738 |
> |
/** |
739 |
> |
* Version of pop that takes top element only if it |
740 |
> |
* its root is the given CountedCompleter. |
741 |
> |
*/ |
742 |
> |
final ForkJoinTask<?> popCC(CountedCompleter<?> root) { |
743 |
> |
ForkJoinTask<?>[] a; int m; |
744 |
> |
if (root != null && (a = array) != null && (m = a.length - 1) >= 0) { |
745 |
> |
for (int s; (s = top - 1) - base >= 0;) { |
746 |
> |
long j = ((m & s) << ASHIFT) + ABASE; |
747 |
> |
ForkJoinTask<?> t = |
748 |
> |
(ForkJoinTask<?>)U.getObject(a, j); |
749 |
> |
if (t == null || !(t instanceof CountedCompleter) || |
750 |
> |
((CountedCompleter<?>)t).getRoot() != root) |
751 |
> |
break; |
752 |
> |
if (U.compareAndSwapObject(a, j, t, null)) { |
753 |
> |
top = s; |
754 |
> |
return t; |
755 |
> |
} |
756 |
> |
if (root.status < 0) |
757 |
> |
break; |
758 |
> |
} |
759 |
> |
} |
760 |
> |
return null; |
761 |
> |
} |
762 |
> |
|
763 |
> |
/** |
764 |
> |
* Shared version of popCC |
765 |
> |
*/ |
766 |
> |
final ForkJoinTask<?> sharedPopCC(CountedCompleter<?> root) { |
767 |
> |
ForkJoinTask<?> task = null; |
768 |
> |
if (root != null && |
769 |
> |
runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) { |
770 |
> |
try { |
771 |
> |
ForkJoinTask<?>[] a; int m; |
772 |
> |
if ((a = array) != null && (m = a.length - 1) >= 0) { |
773 |
> |
for (int s; (s = top - 1) - base >= 0;) { |
774 |
> |
long j = ((m & s) << ASHIFT) + ABASE; |
775 |
> |
ForkJoinTask<?> t = |
776 |
> |
(ForkJoinTask<?>)U.getObject(a, j); |
777 |
> |
if (t == null || !(t instanceof CountedCompleter) || |
778 |
> |
((CountedCompleter<?>)t).getRoot() != root) |
779 |
> |
break; |
780 |
> |
if (U.compareAndSwapObject(a, j, t, null)) { |
781 |
> |
top = s; |
782 |
> |
task = t; |
783 |
> |
break; |
784 |
> |
} |
785 |
> |
if (root.status < 0) |
786 |
> |
break; |
787 |
> |
} |
788 |
> |
} |
789 |
> |
} finally { |
790 |
> |
runState = 0; |
791 |
> |
} |
792 |
> |
} |
793 |
> |
return task; |
794 |
> |
} |
795 |
> |
|
796 |
> |
/** |
797 |
> |
* Takes a task in FIFO order if b is base of queue and a task |
798 |
> |
* can be claimed without contention. Specialized versions |
799 |
> |
* appear in ForkJoinPool methods scan and tryHelpStealer. |
800 |
> |
*/ |
801 |
> |
final ForkJoinTask<?> pollAt(int b) { |
802 |
> |
ForkJoinTask<?> t; ForkJoinTask<?>[] a; |
803 |
> |
if ((a = array) != null) { |
804 |
> |
int j = (((a.length - 1) & b) << ASHIFT) + ABASE; |
805 |
> |
if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) != null && |
806 |
> |
base == b && |
807 |
> |
U.compareAndSwapObject(a, j, t, null)) { |
808 |
> |
base = b + 1; |
809 |
> |
return t; |
810 |
> |
} |
811 |
> |
} |
812 |
> |
return null; |
813 |
> |
} |
814 |
> |
|
815 |
> |
/** |
816 |
> |
* Takes next task, if one exists, in FIFO order. |
817 |
> |
*/ |
818 |
> |
final ForkJoinTask<?> poll() { |
819 |
> |
ForkJoinTask<?>[] a; int b; ForkJoinTask<?> t; |
820 |
> |
while ((b = base) - top < 0 && (a = array) != null) { |
821 |
> |
int j = (((a.length - 1) & b) << ASHIFT) + ABASE; |
822 |
> |
t = (ForkJoinTask<?>)U.getObjectVolatile(a, j); |
823 |
> |
if (t != null) { |
824 |
> |
if (base == b && |
825 |
> |
U.compareAndSwapObject(a, j, t, null)) { |
826 |
> |
base = b + 1; |
827 |
> |
return t; |
828 |
> |
} |
829 |
> |
} |
830 |
> |
else if (base == b) { |
831 |
> |
if (b + 1 == top) |
832 |
> |
break; |
833 |
> |
Thread.yield(); // wait for lagging update |
834 |
> |
} |
835 |
> |
} |
836 |
> |
return null; |
837 |
> |
} |
838 |
> |
|
839 |
> |
/** |
840 |
> |
* Takes next task, if one exists, in order specified by mode. |
841 |
> |
*/ |
842 |
> |
final ForkJoinTask<?> nextLocalTask() { |
843 |
> |
return mode == 0 ? pop() : poll(); |
844 |
> |
} |
845 |
> |
|
846 |
> |
/** |
847 |
> |
* Returns next task, if one exists, in order specified by mode. |
848 |
> |
*/ |
849 |
> |
final ForkJoinTask<?> peek() { |
850 |
> |
ForkJoinTask<?>[] a = array; int m; |
851 |
> |
if (a == null || (m = a.length - 1) < 0) |
852 |
> |
return null; |
853 |
> |
int i = mode == 0 ? top - 1 : base; |
854 |
> |
int j = ((i & m) << ASHIFT) + ABASE; |
855 |
> |
return (ForkJoinTask<?>)U.getObjectVolatile(a, j); |
856 |
> |
} |
857 |
> |
|
858 |
> |
/** |
859 |
> |
* Pops the given task only if it is at the current top. |
860 |
> |
*/ |
861 |
> |
final boolean tryUnpush(ForkJoinTask<?> t) { |
862 |
> |
ForkJoinTask<?>[] a; int s; |
863 |
> |
if ((a = array) != null && (s = top) != base && |
864 |
> |
U.compareAndSwapObject |
865 |
> |
(a, (((a.length - 1) & --s) << ASHIFT) + ABASE, t, null)) { |
866 |
> |
top = s; |
867 |
> |
return true; |
868 |
> |
} |
869 |
> |
return false; |
870 |
> |
} |
871 |
> |
|
872 |
> |
/** |
873 |
> |
* Version of tryUnpush for shared queues; called by non-FJ |
874 |
> |
* submitters after prechecking that task probably exists. |
875 |
> |
*/ |
876 |
> |
final boolean trySharedUnpush(ForkJoinTask<?> t) { |
877 |
> |
boolean success = false; |
878 |
> |
if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) { |
879 |
> |
try { |
880 |
> |
ForkJoinTask<?>[] a; int s; |
881 |
> |
if ((a = array) != null && (s = top) != base && |
882 |
> |
U.compareAndSwapObject |
883 |
> |
(a, (((a.length - 1) & --s) << ASHIFT) + ABASE, t, null)) { |
884 |
> |
top = s; |
885 |
> |
success = true; |
886 |
> |
} |
887 |
> |
} finally { |
888 |
> |
runState = 0; // unlock |
889 |
> |
} |
890 |
> |
} |
891 |
> |
return success; |
892 |
> |
} |
893 |
> |
|
894 |
> |
/** |
895 |
> |
* Polls the given task only if it is at the current base. |
896 |
> |
*/ |
897 |
> |
final boolean pollFor(ForkJoinTask<?> task) { |
898 |
> |
ForkJoinTask<?>[] a; int b; |
899 |
> |
if ((b = base) - top < 0 && (a = array) != null) { |
900 |
> |
int j = (((a.length - 1) & b) << ASHIFT) + ABASE; |
901 |
> |
if (U.getObjectVolatile(a, j) == task && base == b && |
902 |
> |
U.compareAndSwapObject(a, j, task, null)) { |
903 |
> |
base = b + 1; |
904 |
> |
return true; |
905 |
> |
} |
906 |
> |
} |
907 |
> |
return false; |
908 |
> |
} |
909 |
> |
|
910 |
> |
/** |
911 |
> |
* Initializes or doubles the capacity of array. Call either |
912 |
> |
* by owner or with lock held -- it is OK for base, but not |
913 |
> |
* top, to move while resizings are in progress. |
914 |
> |
* |
915 |
> |
* @param rejectOnFailure if true, throw exception if capacity |
916 |
> |
* exceeded (relayed ultimately to user); else return null. |
917 |
> |
*/ |
918 |
> |
final ForkJoinTask<?>[] growArray(boolean rejectOnFailure) { |
919 |
> |
ForkJoinTask<?>[] oldA = array; |
920 |
> |
int size = oldA != null ? oldA.length << 1 : INITIAL_QUEUE_CAPACITY; |
921 |
> |
if (size <= MAXIMUM_QUEUE_CAPACITY) { |
922 |
> |
int oldMask, t, b; |
923 |
> |
ForkJoinTask<?>[] a = array = new ForkJoinTask<?>[size]; |
924 |
> |
if (oldA != null && (oldMask = oldA.length - 1) >= 0 && |
925 |
> |
(t = top) - (b = base) > 0) { |
926 |
> |
int mask = size - 1; |
927 |
> |
do { |
928 |
> |
ForkJoinTask<?> x; |
929 |
> |
int oldj = ((b & oldMask) << ASHIFT) + ABASE; |
930 |
> |
int j = ((b & mask) << ASHIFT) + ABASE; |
931 |
> |
x = (ForkJoinTask<?>)U.getObjectVolatile(oldA, oldj); |
932 |
> |
if (x != null && |
933 |
> |
U.compareAndSwapObject(oldA, oldj, x, null)) |
934 |
> |
U.putObjectVolatile(a, j, x); |
935 |
> |
} while (++b != t); |
936 |
> |
} |
937 |
> |
return a; |
938 |
> |
} |
939 |
> |
else if (!rejectOnFailure) |
940 |
> |
return null; |
941 |
> |
else |
942 |
> |
throw new RejectedExecutionException("Queue capacity exceeded"); |
943 |
> |
} |
944 |
> |
|
945 |
> |
/** |
946 |
> |
* Removes and cancels all known tasks, ignoring any exceptions. |
947 |
> |
*/ |
948 |
> |
final void cancelAll() { |
949 |
> |
ForkJoinTask.cancelIgnoringExceptions(currentJoin); |
950 |
> |
ForkJoinTask.cancelIgnoringExceptions(currentSteal); |
951 |
> |
for (ForkJoinTask<?> t; (t = poll()) != null; ) |
952 |
> |
ForkJoinTask.cancelIgnoringExceptions(t); |
953 |
> |
} |
954 |
> |
|
955 |
> |
/** |
956 |
> |
* Computes next value for random probes. Scans don't require |
957 |
> |
* a very high quality generator, but also not a crummy one. |
958 |
> |
* Marsaglia xor-shift is cheap and works well enough. Note: |
959 |
> |
* This is manually inlined in its usages in ForkJoinPool to |
960 |
> |
* avoid writes inside busy scan loops. |
961 |
> |
*/ |
962 |
> |
final int nextSeed() { |
963 |
> |
int r = seed; |
964 |
> |
r ^= r << 13; |
965 |
> |
r ^= r >>> 17; |
966 |
> |
return seed = r ^= r << 5; |
967 |
> |
} |
968 |
> |
|
969 |
> |
// Execution methods |
970 |
> |
|
971 |
> |
/** |
972 |
> |
* Pops and runs tasks until empty. |
973 |
> |
*/ |
974 |
> |
private void popAndExecAll() { |
975 |
> |
// A bit faster than repeated pop calls |
976 |
> |
ForkJoinTask<?>[] a; int m, s; long j; ForkJoinTask<?> t; |
977 |
> |
while ((a = array) != null && (m = a.length - 1) >= 0 && |
978 |
> |
(s = top - 1) - base >= 0 && |
979 |
> |
(t = ((ForkJoinTask<?>) |
980 |
> |
U.getObject(a, j = ((m & s) << ASHIFT) + ABASE))) |
981 |
> |
!= null) { |
982 |
> |
if (U.compareAndSwapObject(a, j, t, null)) { |
983 |
> |
top = s; |
984 |
> |
t.doExec(); |
985 |
> |
} |
986 |
> |
} |
987 |
> |
} |
988 |
> |
|
989 |
> |
/** |
990 |
> |
* Polls and runs tasks until empty. |
991 |
> |
*/ |
992 |
> |
private void pollAndExecAll() { |
993 |
> |
for (ForkJoinTask<?> t; (t = poll()) != null;) |
994 |
> |
t.doExec(); |
995 |
> |
} |
996 |
> |
|
997 |
> |
/** |
998 |
> |
* If present, removes from queue and executes the given task, or |
999 |
> |
* any other cancelled task. Returns (true) immediately on any CAS |
1000 |
> |
* or consistency check failure so caller can retry. |
1001 |
> |
* |
1002 |
> |
* @return 0 if no progress can be made, else positive |
1003 |
> |
* (this unusual convention simplifies use with tryHelpStealer.) |
1004 |
> |
*/ |
1005 |
> |
final int tryRemoveAndExec(ForkJoinTask<?> task) { |
1006 |
> |
int stat = 1; |
1007 |
> |
boolean removed = false, empty = true; |
1008 |
> |
ForkJoinTask<?>[] a; int m, s, b, n; |
1009 |
> |
if ((a = array) != null && (m = a.length - 1) >= 0 && |
1010 |
> |
(n = (s = top) - (b = base)) > 0) { |
1011 |
> |
for (ForkJoinTask<?> t;;) { // traverse from s to b |
1012 |
> |
int j = ((--s & m) << ASHIFT) + ABASE; |
1013 |
> |
t = (ForkJoinTask<?>)U.getObjectVolatile(a, j); |
1014 |
> |
if (t == null) // inconsistent length |
1015 |
> |
break; |
1016 |
> |
else if (t == task) { |
1017 |
> |
if (s + 1 == top) { // pop |
1018 |
> |
if (!U.compareAndSwapObject(a, j, task, null)) |
1019 |
> |
break; |
1020 |
> |
top = s; |
1021 |
> |
removed = true; |
1022 |
> |
} |
1023 |
> |
else if (base == b) // replace with proxy |
1024 |
> |
removed = U.compareAndSwapObject(a, j, task, |
1025 |
> |
new EmptyTask()); |
1026 |
> |
break; |
1027 |
> |
} |
1028 |
> |
else if (t.status >= 0) |
1029 |
> |
empty = false; |
1030 |
> |
else if (s + 1 == top) { // pop and throw away |
1031 |
> |
if (U.compareAndSwapObject(a, j, t, null)) |
1032 |
> |
top = s; |
1033 |
> |
break; |
1034 |
> |
} |
1035 |
> |
if (--n == 0) { |
1036 |
> |
if (!empty && base == b) |
1037 |
> |
stat = 0; |
1038 |
> |
break; |
1039 |
> |
} |
1040 |
> |
} |
1041 |
> |
} |
1042 |
> |
if (removed) |
1043 |
> |
task.doExec(); |
1044 |
> |
return stat; |
1045 |
> |
} |
1046 |
> |
|
1047 |
> |
/** |
1048 |
> |
* Executes a top-level task and any local tasks remaining |
1049 |
> |
* after execution. |
1050 |
> |
*/ |
1051 |
> |
final void runTask(ForkJoinTask<?> t) { |
1052 |
> |
if (t != null) { |
1053 |
> |
currentSteal = t; |
1054 |
> |
t.doExec(); |
1055 |
> |
if (top != base) { // process remaining local tasks |
1056 |
> |
if (mode == 0) |
1057 |
> |
popAndExecAll(); |
1058 |
> |
else |
1059 |
> |
pollAndExecAll(); |
1060 |
> |
} |
1061 |
> |
++nsteals; |
1062 |
> |
currentSteal = null; |
1063 |
> |
} |
1064 |
> |
} |
1065 |
> |
|
1066 |
> |
/** |
1067 |
> |
* Executes a non-top-level (stolen) task. |
1068 |
> |
*/ |
1069 |
> |
final void runSubtask(ForkJoinTask<?> t) { |
1070 |
> |
if (t != null) { |
1071 |
> |
ForkJoinTask<?> ps = currentSteal; |
1072 |
> |
currentSteal = t; |
1073 |
> |
t.doExec(); |
1074 |
> |
currentSteal = ps; |
1075 |
> |
} |
1076 |
> |
} |
1077 |
> |
|
1078 |
> |
/** |
1079 |
> |
* Returns true if owned and not known to be blocked. |
1080 |
> |
*/ |
1081 |
> |
final boolean isApparentlyUnblocked() { |
1082 |
> |
Thread wt; Thread.State s; |
1083 |
> |
return (eventCount >= 0 && |
1084 |
> |
(wt = owner) != null && |
1085 |
> |
(s = wt.getState()) != Thread.State.BLOCKED && |
1086 |
> |
s != Thread.State.WAITING && |
1087 |
> |
s != Thread.State.TIMED_WAITING); |
1088 |
> |
} |
1089 |
> |
|
1090 |
> |
/** |
1091 |
> |
* If this owned and is not already interrupted, try to |
1092 |
> |
* interrupt and/or unpark, ignoring exceptions. |
1093 |
> |
*/ |
1094 |
> |
final void interruptOwner() { |
1095 |
> |
Thread wt, p; |
1096 |
> |
if ((wt = owner) != null && !wt.isInterrupted()) { |
1097 |
> |
try { |
1098 |
> |
wt.interrupt(); |
1099 |
> |
} catch (SecurityException ignore) { |
1100 |
> |
} |
1101 |
> |
} |
1102 |
> |
if ((p = parker) != null) |
1103 |
> |
U.unpark(p); |
1104 |
> |
} |
1105 |
> |
|
1106 |
> |
// Unsafe mechanics |
1107 |
> |
private static final sun.misc.Unsafe U; |
1108 |
> |
private static final long RUNSTATE; |
1109 |
> |
private static final int ABASE; |
1110 |
> |
private static final int ASHIFT; |
1111 |
> |
static { |
1112 |
> |
int s; |
1113 |
> |
try { |
1114 |
> |
U = getUnsafe(); |
1115 |
> |
Class<?> k = WorkQueue.class; |
1116 |
> |
Class<?> ak = ForkJoinTask[].class; |
1117 |
> |
RUNSTATE = U.objectFieldOffset |
1118 |
> |
(k.getDeclaredField("runState")); |
1119 |
> |
ABASE = U.arrayBaseOffset(ak); |
1120 |
> |
s = U.arrayIndexScale(ak); |
1121 |
> |
} catch (Exception e) { |
1122 |
> |
throw new Error(e); |
1123 |
> |
} |
1124 |
> |
if ((s & (s-1)) != 0) |
1125 |
> |
throw new Error("data type scale not a power of two"); |
1126 |
> |
ASHIFT = 31 - Integer.numberOfLeadingZeros(s); |
1127 |
> |
} |
1128 |
> |
} |
1129 |
|
|
1130 |
|
/** |
1131 |
< |
* If there is a security manager, makes sure caller has |
1132 |
< |
* permission to modify threads. |
1131 |
> |
* Per-thread records for threads that submit to pools. Currently |
1132 |
> |
* holds only pseudo-random seed / index that is used to choose |
1133 |
> |
* submission queues in method doSubmit. In the future, this may |
1134 |
> |
* also incorporate a means to implement different task rejection |
1135 |
> |
* and resubmission policies. |
1136 |
> |
* |
1137 |
> |
* Seeds for submitters and workers/workQueues work in basically |
1138 |
> |
* the same way but are initialized and updated using slightly |
1139 |
> |
* different mechanics. Both are initialized using the same |
1140 |
> |
* approach as in class ThreadLocal, where successive values are |
1141 |
> |
* unlikely to collide with previous values. This is done during |
1142 |
> |
* registration for workers, but requires a separate AtomicInteger |
1143 |
> |
* for submitters. Seeds are then randomly modified upon |
1144 |
> |
* collisions using xorshifts, which requires a non-zero seed. |
1145 |
|
*/ |
1146 |
< |
private static void checkPermission() { |
1147 |
< |
SecurityManager security = System.getSecurityManager(); |
1148 |
< |
if (security != null) |
1149 |
< |
security.checkPermission(modifyThreadPermission); |
1146 |
> |
static final class Submitter { |
1147 |
> |
int seed; |
1148 |
> |
Submitter() { |
1149 |
> |
int s = nextSubmitterSeed.getAndAdd(SEED_INCREMENT); |
1150 |
> |
seed = (s == 0) ? 1 : s; // ensure non-zero |
1151 |
> |
} |
1152 |
> |
} |
1153 |
> |
|
1154 |
> |
/** ThreadLocal class for Submitters */ |
1155 |
> |
static final class ThreadSubmitter extends ThreadLocal<Submitter> { |
1156 |
> |
public Submitter initialValue() { return new Submitter(); } |
1157 |
|
} |
1158 |
|
|
1159 |
+ |
// static fields (initialized in static initializer below) |
1160 |
+ |
|
1161 |
|
/** |
1162 |
< |
* Generator for assigning sequence numbers as pool names. |
1162 |
> |
* Creates a new ForkJoinWorkerThread. This factory is used unless |
1163 |
> |
* overridden in ForkJoinPool constructors. |
1164 |
|
*/ |
1165 |
< |
private static final AtomicInteger poolNumberGenerator; |
1165 |
> |
public static final ForkJoinWorkerThreadFactory |
1166 |
> |
defaultForkJoinWorkerThreadFactory; |
1167 |
> |
|
1168 |
> |
|
1169 |
> |
/** Property prefix for constructing common pool */ |
1170 |
> |
private static final String propPrefix = |
1171 |
> |
"java.util.concurrent.ForkJoinPool.common."; |
1172 |
|
|
1173 |
|
/** |
1174 |
< |
* Generator for initial random seeds for worker victim |
1175 |
< |
* selection. This is used only to create initial seeds. Random |
1176 |
< |
* steals use a cheaper xorshift generator per steal attempt. We |
395 |
< |
* don't expect much contention on seedGenerator, so just use a |
396 |
< |
* plain Random. |
1174 |
> |
* Common (static) pool. Non-null for public use unless a static |
1175 |
> |
* construction exception, but internal usages must null-check on |
1176 |
> |
* use. |
1177 |
|
*/ |
1178 |
< |
static final Random workerSeedGenerator; |
1178 |
> |
static final ForkJoinPool commonPool; |
1179 |
|
|
1180 |
|
/** |
1181 |
< |
* Array holding all worker threads in the pool. Initialized upon |
402 |
< |
* construction. Array size must be a power of two. Updates and |
403 |
< |
* replacements are protected by scanGuard, but the array is |
404 |
< |
* always kept in a consistent enough state to be randomly |
405 |
< |
* accessed without locking by workers performing work-stealing, |
406 |
< |
* as well as other traversal-based methods in this class, so long |
407 |
< |
* as reads memory-acquire by first reading ctl. All readers must |
408 |
< |
* tolerate that some array slots may be null. |
1181 |
> |
* Common pool parallelism. Must equal commonPool.parallelism. |
1182 |
|
*/ |
1183 |
< |
ForkJoinWorkerThread[] workers; |
1183 |
> |
static final int commonPoolParallelism; |
1184 |
|
|
1185 |
|
/** |
1186 |
< |
* Initial size for submission queue array. Must be a power of |
414 |
< |
* two. In many applications, these always stay small so we use a |
415 |
< |
* small initial cap. |
1186 |
> |
* Generator for assigning sequence numbers as pool names. |
1187 |
|
*/ |
1188 |
< |
private static final int INITIAL_QUEUE_CAPACITY = 8; |
1188 |
> |
private static final AtomicInteger poolNumberGenerator; |
1189 |
|
|
1190 |
|
/** |
1191 |
< |
* Maximum size for submission queue array. Must be a power of two |
1192 |
< |
* less than or equal to 1 << (31 - width of array entry) to |
422 |
< |
* ensure lack of index wraparound, but is capped at a lower |
423 |
< |
* value to help users trap runaway computations. |
1191 |
> |
* Generator for initial hashes/seeds for submitters. Accessed by |
1192 |
> |
* Submitter class constructor. |
1193 |
|
*/ |
1194 |
< |
private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 24; // 16M |
1194 |
> |
static final AtomicInteger nextSubmitterSeed; |
1195 |
|
|
1196 |
|
/** |
1197 |
< |
* Array serving as submission queue. Initialized upon construction. |
1197 |
> |
* Permission required for callers of methods that may start or |
1198 |
> |
* kill threads. |
1199 |
|
*/ |
1200 |
< |
private ForkJoinTask<?>[] submissionQueue; |
1200 |
> |
private static final RuntimePermission modifyThreadPermission; |
1201 |
|
|
1202 |
|
/** |
1203 |
< |
* Lock protecting submissions array for addSubmission |
1203 |
> |
* Per-thread submission bookkeeping. Shared across all pools |
1204 |
> |
* to reduce ThreadLocal pollution and because random motion |
1205 |
> |
* to avoid contention in one pool is likely to hold for others. |
1206 |
|
*/ |
1207 |
< |
private final ReentrantLock submissionLock; |
1207 |
> |
private static final ThreadSubmitter submitters; |
1208 |
> |
|
1209 |
> |
// static constants |
1210 |
|
|
1211 |
|
/** |
1212 |
< |
* Condition for awaitTermination, using submissionLock for |
1213 |
< |
* convenience. |
1212 |
> |
* Initial timeout value (in nanoseconds) for the thread triggering |
1213 |
> |
* quiescence to park waiting for new work. On timeout, the thread |
1214 |
> |
* will instead try to shrink the number of workers. |
1215 |
|
*/ |
1216 |
< |
private final Condition termination; |
1216 |
> |
private static final long IDLE_TIMEOUT = 1000L * 1000L * 1000L; // 1sec |
1217 |
|
|
1218 |
|
/** |
1219 |
< |
* Creation factory for worker threads. |
1219 |
> |
* Timeout value when there are more threads than parallelism level |
1220 |
|
*/ |
1221 |
< |
private final ForkJoinWorkerThreadFactory factory; |
1221 |
> |
private static final long FAST_IDLE_TIMEOUT = 100L * 1000L * 1000L; |
1222 |
|
|
1223 |
|
/** |
1224 |
< |
* The uncaught exception handler used when any worker abruptly |
1225 |
< |
* terminates. |
1224 |
> |
* The maximum stolen->joining link depth allowed in method |
1225 |
> |
* tryHelpStealer. Must be a power of two. This value also |
1226 |
> |
* controls the maximum number of times to try to help join a task |
1227 |
> |
* without any apparent progress or change in pool state before |
1228 |
> |
* giving up and blocking (see awaitJoin). Depths for legitimate |
1229 |
> |
* chains are unbounded, but we use a fixed constant to avoid |
1230 |
> |
* (otherwise unchecked) cycles and to bound staleness of |
1231 |
> |
* traversal parameters at the expense of sometimes blocking when |
1232 |
> |
* we could be helping. |
1233 |
|
*/ |
1234 |
< |
final Thread.UncaughtExceptionHandler ueh; |
1234 |
> |
private static final int MAX_HELP = 64; |
1235 |
|
|
1236 |
|
/** |
1237 |
< |
* Prefix for assigning names to worker threads |
1237 |
> |
* Secondary time-based bound (in nanosecs) for helping attempts |
1238 |
> |
* before trying compensated blocking in awaitJoin. Used in |
1239 |
> |
* conjunction with MAX_HELP to reduce variance due to different |
1240 |
> |
* polling rates associated with different helping options. The |
1241 |
> |
* value should roughly approximate the time required to create |
1242 |
> |
* and/or activate a worker thread. |
1243 |
|
*/ |
1244 |
< |
private final String workerNamePrefix; |
1244 |
> |
private static final long COMPENSATION_DELAY = 1L << 18; // ~0.25 millisec |
1245 |
|
|
1246 |
|
/** |
1247 |
< |
* Sum of per-thread steal counts, updated only when threads are |
1248 |
< |
* idle or terminating. |
1247 |
> |
* Increment for seed generators. See class ThreadLocal for |
1248 |
> |
* explanation. |
1249 |
|
*/ |
1250 |
< |
private volatile long stealCount; |
1250 |
> |
private static final int SEED_INCREMENT = 0x61c88647; |
1251 |
|
|
1252 |
|
/** |
1253 |
< |
* Main pool control -- a long packed with: |
1253 |
> |
* Bits and masks for control variables |
1254 |
> |
* |
1255 |
> |
* Field ctl is a long packed with: |
1256 |
|
* AC: Number of active running workers minus target parallelism (16 bits) |
1257 |
|
* TC: Number of total workers minus target parallelism (16 bits) |
1258 |
|
* ST: true if pool is terminating (1 bit) |
1259 |
|
* EC: the wait count of top waiting thread (15 bits) |
1260 |
< |
* ID: ~poolIndex of top of Treiber stack of waiting threads (16 bits) |
1260 |
> |
* ID: poolIndex of top of Treiber stack of waiters (16 bits) |
1261 |
|
* |
1262 |
|
* When convenient, we can extract the upper 32 bits of counts and |
1263 |
|
* the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e = |
1266 |
|
* parallelism and the positionings of fields makes it possible to |
1267 |
|
* perform the most common checks via sign tests of fields: When |
1268 |
|
* ac is negative, there are not enough active workers, when tc is |
1269 |
< |
* negative, there are not enough total workers, when id is |
481 |
< |
* negative, there is at least one waiting worker, and when e is |
1269 |
> |
* negative, there are not enough total workers, and when e is |
1270 |
|
* negative, the pool is terminating. To deal with these possibly |
1271 |
|
* negative fields, we use casts in and out of "short" and/or |
1272 |
|
* signed shifts to maintain signedness. |
1273 |
+ |
* |
1274 |
+ |
* When a thread is queued (inactivated), its eventCount field is |
1275 |
+ |
* set negative, which is the only way to tell if a worker is |
1276 |
+ |
* prevented from executing tasks, even though it must continue to |
1277 |
+ |
* scan for them to avoid queuing races. Note however that |
1278 |
+ |
* eventCount updates lag releases so usage requires care. |
1279 |
+ |
* |
1280 |
+ |
* Field runState is an int packed with: |
1281 |
+ |
* SHUTDOWN: true if shutdown is enabled (1 bit) |
1282 |
+ |
* SEQ: a sequence number updated upon (de)registering workers (30 bits) |
1283 |
+ |
* INIT: set true after workQueues array construction (1 bit) |
1284 |
+ |
* |
1285 |
+ |
* The sequence number enables simple consistency checks: |
1286 |
+ |
* Staleness of read-only operations on the workQueues array can |
1287 |
+ |
* be checked by comparing runState before vs after the reads. |
1288 |
|
*/ |
486 |
– |
volatile long ctl; |
1289 |
|
|
1290 |
|
// bit positions/shifts for fields |
1291 |
|
private static final int AC_SHIFT = 48; |
1294 |
|
private static final int EC_SHIFT = 16; |
1295 |
|
|
1296 |
|
// bounds |
1297 |
< |
private static final int MAX_ID = 0x7fff; // max poolIndex |
1298 |
< |
private static final int SMASK = 0xffff; // mask short bits |
1297 |
> |
private static final int SMASK = 0xffff; // short bits |
1298 |
> |
private static final int MAX_CAP = 0x7fff; // max #workers - 1 |
1299 |
> |
private static final int SQMASK = 0xfffe; // even short bits |
1300 |
|
private static final int SHORT_SIGN = 1 << 15; |
1301 |
|
private static final int INT_SIGN = 1 << 31; |
1302 |
|
|
1318 |
|
private static final int UTC_UNIT = 1 << UTC_SHIFT; |
1319 |
|
|
1320 |
|
// masks and units for dealing with e = (int)ctl |
1321 |
< |
private static final int E_MASK = 0x7fffffff; // no STOP_BIT |
1322 |
< |
private static final int EC_UNIT = 1 << EC_SHIFT; |
520 |
< |
|
521 |
< |
/** |
522 |
< |
* The target parallelism level. |
523 |
< |
*/ |
524 |
< |
final int parallelism; |
525 |
< |
|
526 |
< |
/** |
527 |
< |
* Index (mod submission queue length) of next element to take |
528 |
< |
* from submission queue. Usage is identical to that for |
529 |
< |
* per-worker queues -- see ForkJoinWorkerThread internal |
530 |
< |
* documentation. |
531 |
< |
*/ |
532 |
< |
volatile int queueBase; |
533 |
< |
|
534 |
< |
/** |
535 |
< |
* Index (mod submission queue length) of next element to add |
536 |
< |
* in submission queue. Usage is identical to that for |
537 |
< |
* per-worker queues -- see ForkJoinWorkerThread internal |
538 |
< |
* documentation. |
539 |
< |
*/ |
540 |
< |
int queueTop; |
541 |
< |
|
542 |
< |
/** |
543 |
< |
* True when shutdown() has been called. |
544 |
< |
*/ |
545 |
< |
volatile boolean shutdown; |
546 |
< |
|
547 |
< |
/** |
548 |
< |
* True if use local fifo, not default lifo, for local polling. |
549 |
< |
* Read by, and replicated by ForkJoinWorkerThreads. |
550 |
< |
*/ |
551 |
< |
final boolean locallyFifo; |
552 |
< |
|
553 |
< |
/** |
554 |
< |
* The number of threads in ForkJoinWorkerThreads.helpQuiescePool. |
555 |
< |
* When non-zero, suppresses automatic shutdown when active |
556 |
< |
* counts become zero. |
557 |
< |
*/ |
558 |
< |
volatile int quiescerCount; |
559 |
< |
|
560 |
< |
/** |
561 |
< |
* The number of threads blocked in join. |
562 |
< |
*/ |
563 |
< |
volatile int blockedCount; |
564 |
< |
|
565 |
< |
/** |
566 |
< |
* Counter for worker Thread names (unrelated to their poolIndex) |
567 |
< |
*/ |
568 |
< |
private volatile int nextWorkerNumber; |
569 |
< |
|
570 |
< |
/** |
571 |
< |
* The index for the next created worker. Accessed under scanGuard. |
572 |
< |
*/ |
573 |
< |
private int nextWorkerIndex; |
1321 |
> |
private static final int E_MASK = 0x7fffffff; // no STOP_BIT |
1322 |
> |
private static final int E_SEQ = 1 << EC_SHIFT; |
1323 |
|
|
1324 |
< |
/** |
1325 |
< |
* SeqLock and index masking for updates to workers array. Locked |
577 |
< |
* when SG_UNIT is set. Unlocking clears bit by adding |
578 |
< |
* SG_UNIT. Staleness of read-only operations can be checked by |
579 |
< |
* comparing scanGuard to value before the reads. The low 16 bits |
580 |
< |
* (i.e, anding with SMASK) hold (the smallest power of two |
581 |
< |
* covering all worker indices, minus one, and is used to avoid |
582 |
< |
* dealing with large numbers of null slots when the workers array |
583 |
< |
* is overallocated. |
584 |
< |
*/ |
585 |
< |
volatile int scanGuard; |
1324 |
> |
// runState bits |
1325 |
> |
private static final int SHUTDOWN = 1 << 31; |
1326 |
|
|
1327 |
< |
private static final int SG_UNIT = 1 << 16; |
1328 |
< |
|
1329 |
< |
/** |
1330 |
< |
* The wakeup interval (in nanoseconds) for a worker waiting for a |
591 |
< |
* task when the pool is quiescent to instead try to shrink the |
592 |
< |
* number of workers. The exact value does not matter too |
593 |
< |
* much. It must be short enough to release resources during |
594 |
< |
* sustained periods of idleness, but not so short that threads |
595 |
< |
* are continually re-created. |
596 |
< |
*/ |
597 |
< |
private static final long SHRINK_RATE = |
598 |
< |
4L * 1000L * 1000L * 1000L; // 4 seconds |
1327 |
> |
// access mode for WorkQueue |
1328 |
> |
static final int LIFO_QUEUE = 0; |
1329 |
> |
static final int FIFO_QUEUE = 1; |
1330 |
> |
static final int SHARED_QUEUE = -1; |
1331 |
|
|
1332 |
< |
/** |
601 |
< |
* Top-level loop for worker threads: On each step: if the |
602 |
< |
* previous step swept through all queues and found no tasks, or |
603 |
< |
* there are excess threads, then possibly blocks. Otherwise, |
604 |
< |
* scans for and, if found, executes a task. Returns when pool |
605 |
< |
* and/or worker terminate. |
606 |
< |
* |
607 |
< |
* @param w the worker |
608 |
< |
*/ |
609 |
< |
final void work(ForkJoinWorkerThread w) { |
610 |
< |
boolean swept = false; // true on empty scans |
611 |
< |
long c; |
612 |
< |
while (!w.terminate && (int)(c = ctl) >= 0) { |
613 |
< |
int a; // active count |
614 |
< |
if (!swept && (a = (int)(c >> AC_SHIFT)) <= 0) |
615 |
< |
swept = scan(w, a); |
616 |
< |
else if (tryAwaitWork(w, c)) |
617 |
< |
swept = false; |
618 |
< |
} |
619 |
< |
} |
1332 |
> |
// Instance fields |
1333 |
|
|
1334 |
< |
// Signalling |
1334 |
> |
/* |
1335 |
> |
* Field layout order in this class tends to matter more than one |
1336 |
> |
* would like. Runtime layout order is only loosely related to |
1337 |
> |
* declaration order and may differ across JVMs, but the following |
1338 |
> |
* empirically works OK on current JVMs. |
1339 |
> |
*/ |
1340 |
> |
|
1341 |
> |
volatile long stealCount; // collects worker counts |
1342 |
> |
volatile long ctl; // main pool control |
1343 |
> |
final int parallelism; // parallelism level |
1344 |
> |
final int localMode; // per-worker scheduling mode |
1345 |
> |
volatile int nextWorkerNumber; // to create worker name string |
1346 |
> |
final int submitMask; // submit queue index bound |
1347 |
> |
int nextSeed; // for initializing worker seeds |
1348 |
> |
volatile int mainLock; // spinlock for array updates |
1349 |
> |
volatile int runState; // shutdown status and seq |
1350 |
> |
WorkQueue[] workQueues; // main registry |
1351 |
> |
final ForkJoinWorkerThreadFactory factory; // factory for new workers |
1352 |
> |
final Thread.UncaughtExceptionHandler ueh; // per-worker UEH |
1353 |
> |
final String workerNamePrefix; // to create worker name string |
1354 |
|
|
1355 |
< |
/** |
1356 |
< |
* Wakes up or creates a worker. |
1357 |
< |
*/ |
1358 |
< |
final void signalWork() { |
1359 |
< |
/* |
1360 |
< |
* The while condition is true if: (there is are too few total |
1361 |
< |
* workers OR there is at least one waiter) AND (there are too |
1362 |
< |
* few active workers OR the pool is terminating). The value |
1363 |
< |
* of e distinguishes the remaining cases: zero (no waiters) |
1364 |
< |
* for create, negative if terminating (in which case do |
1365 |
< |
* nothing), else release a waiter. The secondary checks for |
1366 |
< |
* release (non-null array etc) can fail if the pool begins |
1367 |
< |
* terminating after the test, and don't impose any added cost |
1368 |
< |
* because JVMs must perform null and bounds checks anyway. |
1369 |
< |
*/ |
1370 |
< |
long c; int e, u; |
1371 |
< |
while ((((e = (int)(c = ctl)) | (u = (int)(c >>> 32))) & |
1372 |
< |
(INT_SIGN|SHORT_SIGN)) == (INT_SIGN|SHORT_SIGN) && e >= 0) { |
1373 |
< |
if (e > 0) { // release a waiting worker |
1374 |
< |
int i; ForkJoinWorkerThread w; ForkJoinWorkerThread[] ws; |
1375 |
< |
if ((ws = workers) == null || |
1376 |
< |
(i = ~e & SMASK) >= ws.length || |
1377 |
< |
(w = ws[i]) == null) |
1378 |
< |
break; |
1379 |
< |
long nc = (((long)(w.nextWait & E_MASK)) | |
1380 |
< |
((long)(u + UAC_UNIT) << 32)); |
1381 |
< |
if (w.eventCount == e && |
1382 |
< |
UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) { |
1383 |
< |
w.eventCount = (e + EC_UNIT) & E_MASK; |
1384 |
< |
if (w.parked) |
1385 |
< |
UNSAFE.unpark(w); |
1386 |
< |
break; |
1355 |
> |
/* |
1356 |
> |
* Mechanics for main lock protecting worker array updates. Uses |
1357 |
> |
* the same strategy as ConcurrentHashMap bins -- a spinLock for |
1358 |
> |
* normal cases, but falling back to builtin lock when (rarely) |
1359 |
> |
* needed. See internal ConcurrentHashMap documentation for |
1360 |
> |
* explanation. |
1361 |
> |
*/ |
1362 |
> |
|
1363 |
> |
static final int LOCK_WAITING = 2; // bit to indicate need for signal |
1364 |
> |
static final int MAX_LOCK_SPINS = 1 << 8; |
1365 |
> |
|
1366 |
> |
private void tryAwaitMainLock() { |
1367 |
> |
int spins = MAX_LOCK_SPINS, r = 0, h; |
1368 |
> |
while (((h = mainLock) & 1) != 0) { |
1369 |
> |
if (r == 0) |
1370 |
> |
r = ThreadLocalRandom.current().nextInt(); // randomize spins |
1371 |
> |
else if (spins >= 0) { |
1372 |
> |
r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift |
1373 |
> |
if (r >= 0) |
1374 |
> |
--spins; |
1375 |
> |
} |
1376 |
> |
else if (U.compareAndSwapInt(this, MAINLOCK, h, h | LOCK_WAITING)) { |
1377 |
> |
synchronized (this) { |
1378 |
> |
if ((mainLock & LOCK_WAITING) != 0) { |
1379 |
> |
try { |
1380 |
> |
wait(); |
1381 |
> |
} catch (InterruptedException ie) { |
1382 |
> |
Thread.currentThread().interrupt(); |
1383 |
> |
} |
1384 |
> |
} |
1385 |
> |
else |
1386 |
> |
notifyAll(); // possibly won race vs signaller |
1387 |
|
} |
656 |
– |
} |
657 |
– |
else if (UNSAFE.compareAndSwapLong |
658 |
– |
(this, ctlOffset, c, |
659 |
– |
(long)(((u + UTC_UNIT) & UTC_MASK) | |
660 |
– |
((u + UAC_UNIT) & UAC_MASK)) << 32)) { |
661 |
– |
addWorker(); |
1388 |
|
break; |
1389 |
|
} |
1390 |
|
} |
1391 |
|
} |
1392 |
|
|
1393 |
+ |
// Creating, registering, and deregistering workers |
1394 |
+ |
|
1395 |
|
/** |
1396 |
< |
* Variant of signalWork to help release waiters on rescans. |
669 |
< |
* Tries once to release a waiter if active count < 0. |
670 |
< |
* |
671 |
< |
* @return false if failed due to contention, else true |
1396 |
> |
* Tries to create and start a worker |
1397 |
|
*/ |
1398 |
< |
private boolean tryReleaseWaiter() { |
1399 |
< |
long c; int e, i; ForkJoinWorkerThread w; ForkJoinWorkerThread[] ws; |
1400 |
< |
if ((e = (int)(c = ctl)) > 0 && |
1401 |
< |
(int)(c >> AC_SHIFT) < 0 && |
1402 |
< |
(ws = workers) != null && |
1403 |
< |
(i = ~e & SMASK) < ws.length && |
1404 |
< |
(w = ws[i]) != null) { |
1405 |
< |
long nc = ((long)(w.nextWait & E_MASK) | |
1406 |
< |
((c + AC_UNIT) & (AC_MASK|TC_MASK))); |
1407 |
< |
if (w.eventCount != e || |
683 |
< |
!UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) |
684 |
< |
return false; |
685 |
< |
w.eventCount = (e + EC_UNIT) & E_MASK; |
686 |
< |
if (w.parked) |
687 |
< |
UNSAFE.unpark(w); |
1398 |
> |
private void addWorker() { |
1399 |
> |
Throwable ex = null; |
1400 |
> |
ForkJoinWorkerThread wt = null; |
1401 |
> |
try { |
1402 |
> |
if ((wt = factory.newThread(this)) != null) { |
1403 |
> |
wt.start(); |
1404 |
> |
return; |
1405 |
> |
} |
1406 |
> |
} catch (Throwable e) { |
1407 |
> |
ex = e; |
1408 |
|
} |
1409 |
< |
return true; |
1409 |
> |
deregisterWorker(wt, ex); // adjust counts etc on failure |
1410 |
|
} |
1411 |
|
|
692 |
– |
// Scanning for tasks |
693 |
– |
|
1412 |
|
/** |
1413 |
< |
* Scans for and, if found, executes one task. Scans start at a |
1414 |
< |
* random index of workers array, and randomly select the first |
1415 |
< |
* (2*#workers)-1 probes, and then, if all empty, resort to 2 |
1416 |
< |
* circular sweeps, which is necessary to check quiescence. and |
1417 |
< |
* taking a submission only if no stealable tasks were found. The |
1418 |
< |
* steal code inside the loop is a specialized form of |
1419 |
< |
* ForkJoinWorkerThread.deqTask, followed bookkeeping to support |
1420 |
< |
* helpJoinTask and signal propagation. The code for submission |
1421 |
< |
* queues is almost identical. On each steal, the worker completes |
1422 |
< |
* not only the task, but also all local tasks that this task may |
705 |
< |
* have generated. On detecting staleness or contention when |
706 |
< |
* trying to take a task, this method returns without finishing |
707 |
< |
* sweep, which allows global state rechecks before retry. |
708 |
< |
* |
709 |
< |
* @param w the worker |
710 |
< |
* @param a the number of active workers |
711 |
< |
* @return true if swept all queues without finding a task |
712 |
< |
*/ |
713 |
< |
private boolean scan(ForkJoinWorkerThread w, int a) { |
714 |
< |
int g = scanGuard; // mask 0 avoids useless scans if only one active |
715 |
< |
int m = (parallelism == 1 - a && blockedCount == 0) ? 0 : g & SMASK; |
716 |
< |
ForkJoinWorkerThread[] ws = workers; |
717 |
< |
if (ws == null || ws.length <= m) // staleness check |
718 |
< |
return false; |
719 |
< |
for (int r = w.seed, k = r, j = -(m + m); j <= m + m; ++j) { |
720 |
< |
ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i; |
721 |
< |
ForkJoinWorkerThread v = ws[k & m]; |
722 |
< |
if (v != null && (b = v.queueBase) != v.queueTop && |
723 |
< |
(q = v.queue) != null && (i = (q.length - 1) & b) >= 0) { |
724 |
< |
long u = (i << ASHIFT) + ABASE; |
725 |
< |
if ((t = q[i]) != null && v.queueBase == b && |
726 |
< |
UNSAFE.compareAndSwapObject(q, u, t, null)) { |
727 |
< |
int d = (v.queueBase = b + 1) - v.queueTop; |
728 |
< |
v.stealHint = w.poolIndex; |
729 |
< |
if (d != 0) |
730 |
< |
signalWork(); // propagate if nonempty |
731 |
< |
w.execTask(t); |
732 |
< |
} |
733 |
< |
r ^= r << 13; r ^= r >>> 17; w.seed = r ^ (r << 5); |
734 |
< |
return false; // store next seed |
735 |
< |
} |
736 |
< |
else if (j < 0) { // xorshift |
737 |
< |
r ^= r << 13; r ^= r >>> 17; k = r ^= r << 5; |
738 |
< |
} |
739 |
< |
else |
740 |
< |
++k; |
741 |
< |
} |
742 |
< |
if (scanGuard != g) // staleness check |
743 |
< |
return false; |
744 |
< |
else { // try to take submission |
745 |
< |
ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i; |
746 |
< |
if ((b = queueBase) != queueTop && |
747 |
< |
(q = submissionQueue) != null && |
748 |
< |
(i = (q.length - 1) & b) >= 0) { |
749 |
< |
long u = (i << ASHIFT) + ABASE; |
750 |
< |
if ((t = q[i]) != null && queueBase == b && |
751 |
< |
UNSAFE.compareAndSwapObject(q, u, t, null)) { |
752 |
< |
queueBase = b + 1; |
753 |
< |
w.execTask(t); |
754 |
< |
} |
755 |
< |
return false; |
756 |
< |
} |
757 |
< |
return true; // all queues empty |
758 |
< |
} |
1413 |
> |
* Callback from ForkJoinWorkerThread constructor to assign a |
1414 |
> |
* public name. This must be separate from registerWorker because |
1415 |
> |
* it is called during the "super" constructor call in |
1416 |
> |
* ForkJoinWorkerThread. |
1417 |
> |
*/ |
1418 |
> |
final String nextWorkerName() { |
1419 |
> |
int n; |
1420 |
> |
do {} while (!U.compareAndSwapInt(this, NEXTWORKERNUMBER, |
1421 |
> |
n = nextWorkerNumber, ++n)); |
1422 |
> |
return workerNamePrefix.concat(Integer.toString(n)); |
1423 |
|
} |
1424 |
|
|
1425 |
|
/** |
1426 |
< |
* Tries to enqueue worker w in wait queue and await change in |
1427 |
< |
* worker's eventCount. If the pool is quiescent and there is |
1428 |
< |
* more than one worker, possibly terminates worker upon exit. |
1429 |
< |
* Otherwise, before blocking, rescans queues to avoid missed |
1430 |
< |
* signals. Upon finding work, releases at least one worker |
767 |
< |
* (which may be the current worker). Rescans restart upon |
768 |
< |
* detected staleness or failure to release due to |
769 |
< |
* contention. Note the unusual conventions about Thread.interrupt |
770 |
< |
* here and elsewhere: Because interrupts are used solely to alert |
771 |
< |
* threads to check termination, which is checked here anyway, we |
772 |
< |
* clear status (using Thread.interrupted) before any call to |
773 |
< |
* park, so that park does not immediately return due to status |
774 |
< |
* being set via some other unrelated call to interrupt in user |
775 |
< |
* code. |
1426 |
> |
* Callback from ForkJoinWorkerThread constructor to establish its |
1427 |
> |
* poolIndex and record its WorkQueue. To avoid scanning bias due |
1428 |
> |
* to packing entries in front of the workQueues array, we treat |
1429 |
> |
* the array as a simple power-of-two hash table using per-thread |
1430 |
> |
* seed as hash, expanding as needed. |
1431 |
|
* |
1432 |
< |
* @param w the calling worker |
778 |
< |
* @param c the ctl value on entry |
779 |
< |
* @return true if waited or another thread was released upon enq |
1432 |
> |
* @param w the worker's queue |
1433 |
|
*/ |
1434 |
< |
private boolean tryAwaitWork(ForkJoinWorkerThread w, long c) { |
1435 |
< |
int v = w.eventCount; |
1436 |
< |
w.nextWait = (int)c; // w's successor record |
1437 |
< |
long nc = (long)(v & E_MASK) | ((c - AC_UNIT) & (AC_MASK|TC_MASK)); |
1438 |
< |
if (ctl != c || !UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) { |
1439 |
< |
long d = ctl; // return true if lost to a deq, to force scan |
1440 |
< |
return (int)d != (int)c && ((d - c) & AC_MASK) >= 0L; |
1441 |
< |
} |
1442 |
< |
for (int sc = w.stealCount; sc != 0;) { // accumulate stealCount |
1443 |
< |
long s = stealCount; |
1444 |
< |
if (UNSAFE.compareAndSwapLong(this, stealCountOffset, s, s + sc)) |
1445 |
< |
sc = w.stealCount = 0; |
1446 |
< |
else if (w.eventCount != v) |
1447 |
< |
return true; // update next time |
1448 |
< |
} |
1449 |
< |
if ((!shutdown || !tryTerminate(false)) && |
1450 |
< |
(int)c != 0 && parallelism + (int)(nc >> AC_SHIFT) == 0 && |
1451 |
< |
blockedCount == 0 && quiescerCount == 0) |
1452 |
< |
idleAwaitWork(w, nc, c, v); // quiescent |
1453 |
< |
for (boolean rescanned = false;;) { |
801 |
< |
if (w.eventCount != v) |
802 |
< |
return true; |
803 |
< |
if (!rescanned) { |
804 |
< |
int g = scanGuard, m = g & SMASK; |
805 |
< |
ForkJoinWorkerThread[] ws = workers; |
806 |
< |
if (ws != null && m < ws.length) { |
807 |
< |
rescanned = true; |
808 |
< |
for (int i = 0; i <= m; ++i) { |
809 |
< |
ForkJoinWorkerThread u = ws[i]; |
810 |
< |
if (u != null) { |
811 |
< |
if (u.queueBase != u.queueTop && |
812 |
< |
!tryReleaseWaiter()) |
813 |
< |
rescanned = false; // contended |
814 |
< |
if (w.eventCount != v) |
815 |
< |
return true; |
1434 |
> |
final void registerWorker(WorkQueue w) { |
1435 |
> |
while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1)) |
1436 |
> |
tryAwaitMainLock(); |
1437 |
> |
try { |
1438 |
> |
WorkQueue[] ws; |
1439 |
> |
if ((ws = workQueues) == null) |
1440 |
> |
ws = workQueues = new WorkQueue[submitMask + 1]; |
1441 |
> |
if (w != null) { |
1442 |
> |
int rs, n = ws.length, m = n - 1; |
1443 |
> |
int s = nextSeed += SEED_INCREMENT; // rarely-colliding sequence |
1444 |
> |
w.seed = (s == 0) ? 1 : s; // ensure non-zero seed |
1445 |
> |
int r = (s << 1) | 1; // use odd-numbered indices |
1446 |
> |
if (ws[r &= m] != null) { // collision |
1447 |
> |
int probes = 0; // step by approx half size |
1448 |
> |
int step = (n <= 4) ? 2 : ((n >>> 1) & SQMASK) + 2; |
1449 |
> |
while (ws[r = (r + step) & m] != null) { |
1450 |
> |
if (++probes >= n) { |
1451 |
> |
workQueues = ws = Arrays.copyOf(ws, n <<= 1); |
1452 |
> |
m = n - 1; |
1453 |
> |
probes = 0; |
1454 |
|
} |
1455 |
|
} |
1456 |
|
} |
1457 |
< |
if (scanGuard != g || // stale |
1458 |
< |
(queueBase != queueTop && !tryReleaseWaiter())) |
1459 |
< |
rescanned = false; |
822 |
< |
if (!rescanned) |
823 |
< |
Thread.yield(); // reduce contention |
824 |
< |
else |
825 |
< |
Thread.interrupted(); // clear before park |
1457 |
> |
w.eventCount = w.poolIndex = r; // establish before recording |
1458 |
> |
ws[r] = w; // also update seq |
1459 |
> |
runState = ((rs = runState) & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN); |
1460 |
|
} |
1461 |
< |
else { |
1462 |
< |
w.parked = true; // must recheck |
1463 |
< |
if (w.eventCount != v) { |
1464 |
< |
w.parked = false; |
831 |
< |
return true; |
832 |
< |
} |
833 |
< |
LockSupport.park(this); |
834 |
< |
rescanned = w.parked = false; |
1461 |
> |
} finally { |
1462 |
> |
if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) { |
1463 |
> |
mainLock = 0; |
1464 |
> |
synchronized (this) { notifyAll(); }; |
1465 |
|
} |
1466 |
|
} |
1467 |
+ |
|
1468 |
|
} |
1469 |
|
|
1470 |
|
/** |
1471 |
< |
* If inactivating worker w has caused pool to become |
1472 |
< |
* quiescent, check for pool termination, and wait for event |
1473 |
< |
* for up to SHRINK_RATE nanosecs (rescans are unnecessary in |
1474 |
< |
* this case because quiescence reflects consensus about lack |
844 |
< |
* of work). On timeout, if ctl has not changed, terminate the |
845 |
< |
* worker. Upon its termination (see deregisterWorker), it may |
846 |
< |
* wake up another worker to possibly repeat this process. |
1471 |
> |
* Final callback from terminating worker, as well as upon failure |
1472 |
> |
* to construct or start a worker in addWorker. Removes record of |
1473 |
> |
* worker from array, and adjusts counts. If pool is shutting |
1474 |
> |
* down, tries to complete termination. |
1475 |
|
* |
1476 |
< |
* @param w the calling worker |
1477 |
< |
* @param currentCtl the ctl value after enqueuing w |
1478 |
< |
* @param prevCtl the ctl value if w terminated |
1479 |
< |
* @param v the eventCount w awaits change |
1480 |
< |
*/ |
1481 |
< |
private void idleAwaitWork(ForkJoinWorkerThread w, long currentCtl, |
1482 |
< |
long prevCtl, int v) { |
1483 |
< |
if (w.eventCount == v) { |
1484 |
< |
if (shutdown) |
1485 |
< |
tryTerminate(false); |
1486 |
< |
ForkJoinTask.helpExpungeStaleExceptions(); // help clean weak refs |
1487 |
< |
while (ctl == currentCtl) { |
1488 |
< |
long startTime = System.nanoTime(); |
1489 |
< |
w.parked = true; |
1490 |
< |
if (w.eventCount == v) // must recheck |
1491 |
< |
LockSupport.parkNanos(this, SHRINK_RATE); |
1492 |
< |
w.parked = false; |
1493 |
< |
if (w.eventCount != v) |
1494 |
< |
break; |
1495 |
< |
else if (System.nanoTime() - startTime < |
1496 |
< |
SHRINK_RATE - (SHRINK_RATE / 10)) // timing slop |
869 |
< |
Thread.interrupted(); // spurious wakeup |
870 |
< |
else if (UNSAFE.compareAndSwapLong(this, ctlOffset, |
871 |
< |
currentCtl, prevCtl)) { |
872 |
< |
w.terminate = true; // restore previous |
873 |
< |
w.eventCount = ((int)currentCtl + EC_UNIT) & E_MASK; |
874 |
< |
break; |
1476 |
> |
* @param wt the worker thread or null if addWorker failed |
1477 |
> |
* @param ex the exception causing failure, or null if none |
1478 |
> |
*/ |
1479 |
> |
final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) { |
1480 |
> |
WorkQueue w = null; |
1481 |
> |
if (wt != null && (w = wt.workQueue) != null) { |
1482 |
> |
w.runState = -1; // ensure runState is set |
1483 |
> |
long steals = w.totalSteals + w.nsteals, sc; |
1484 |
> |
do {} while (!U.compareAndSwapLong(this, STEALCOUNT, |
1485 |
> |
sc = stealCount, sc + steals)); |
1486 |
> |
int idx = w.poolIndex; |
1487 |
> |
while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1)) |
1488 |
> |
tryAwaitMainLock(); |
1489 |
> |
try { |
1490 |
> |
WorkQueue[] ws = workQueues; |
1491 |
> |
if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w) |
1492 |
> |
ws[idx] = null; |
1493 |
> |
} finally { |
1494 |
> |
if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) { |
1495 |
> |
mainLock = 0; |
1496 |
> |
synchronized (this) { notifyAll(); }; |
1497 |
|
} |
1498 |
|
} |
1499 |
|
} |
1500 |
+ |
|
1501 |
+ |
long c; // adjust ctl counts |
1502 |
+ |
do {} while (!U.compareAndSwapLong |
1503 |
+ |
(this, CTL, c = ctl, (((c - AC_UNIT) & AC_MASK) | |
1504 |
+ |
((c - TC_UNIT) & TC_MASK) | |
1505 |
+ |
(c & ~(AC_MASK|TC_MASK))))); |
1506 |
+ |
|
1507 |
+ |
if (!tryTerminate(false, false) && w != null) { |
1508 |
+ |
w.cancelAll(); // cancel remaining tasks |
1509 |
+ |
if (w.array != null) // suppress signal if never ran |
1510 |
+ |
signalWork(); // wake up or create replacement |
1511 |
+ |
if (ex == null) // help clean refs on way out |
1512 |
+ |
ForkJoinTask.helpExpungeStaleExceptions(); |
1513 |
+ |
} |
1514 |
+ |
|
1515 |
+ |
if (ex != null) // rethrow |
1516 |
+ |
U.throwException(ex); |
1517 |
|
} |
1518 |
|
|
1519 |
|
// Submissions |
1520 |
|
|
1521 |
|
/** |
1522 |
< |
* Enqueues the given task in the submissionQueue. Same idea as |
1523 |
< |
* ForkJoinWorkerThread.pushTask except for use of submissionLock. |
1524 |
< |
* |
1525 |
< |
* @param t the task |
1526 |
< |
*/ |
1527 |
< |
private void addSubmission(ForkJoinTask<?> t) { |
1528 |
< |
final ReentrantLock lock = this.submissionLock; |
1529 |
< |
lock.lock(); |
1530 |
< |
try { |
1531 |
< |
ForkJoinTask<?>[] q; int s, m; |
1532 |
< |
if ((q = submissionQueue) != null) { // ignore if queue removed |
1533 |
< |
long u = (((s = queueTop) & (m = q.length-1)) << ASHIFT)+ABASE; |
1534 |
< |
UNSAFE.putOrderedObject(q, u, t); |
1535 |
< |
queueTop = s + 1; |
1536 |
< |
if (s - queueBase == m) |
1537 |
< |
growSubmissionQueue(); |
1522 |
> |
* Unless shutting down, adds the given task to a submission queue |
1523 |
> |
* at submitter's current queue index (modulo submission |
1524 |
> |
* range). If no queue exists at the index, one is created. If |
1525 |
> |
* the queue is busy, another index is randomly chosen. The |
1526 |
> |
* submitMask bounds the effective number of queues to the |
1527 |
> |
* (nearest power of two for) parallelism level. |
1528 |
> |
* |
1529 |
> |
* @param task the task. Caller must ensure non-null. |
1530 |
> |
*/ |
1531 |
> |
private void doSubmit(ForkJoinTask<?> task) { |
1532 |
> |
Submitter s = submitters.get(); |
1533 |
> |
for (int r = s.seed, m = submitMask;;) { |
1534 |
> |
WorkQueue[] ws; WorkQueue q; |
1535 |
> |
int k = r & m & SQMASK; // use only even indices |
1536 |
> |
if (runState < 0) |
1537 |
> |
throw new RejectedExecutionException(); // shutting down |
1538 |
> |
else if ((ws = workQueues) == null || ws.length <= k) { |
1539 |
> |
while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1)) |
1540 |
> |
tryAwaitMainLock(); |
1541 |
> |
try { |
1542 |
> |
if (workQueues == null) |
1543 |
> |
workQueues = new WorkQueue[submitMask + 1]; |
1544 |
> |
} finally { |
1545 |
> |
if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) { |
1546 |
> |
mainLock = 0; |
1547 |
> |
synchronized (this) { notifyAll(); }; |
1548 |
> |
} |
1549 |
> |
} |
1550 |
|
} |
1551 |
< |
} finally { |
1552 |
< |
lock.unlock(); |
1551 |
> |
else if ((q = ws[k]) == null) { // create new queue |
1552 |
> |
WorkQueue nq = new WorkQueue(this, null, SHARED_QUEUE); |
1553 |
> |
while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1)) |
1554 |
> |
tryAwaitMainLock(); |
1555 |
> |
try { |
1556 |
> |
int rs = runState; // to update seq |
1557 |
> |
if (ws == workQueues && ws[k] == null) { |
1558 |
> |
ws[k] = nq; |
1559 |
> |
runState = ((rs & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN)); |
1560 |
> |
} |
1561 |
> |
} finally { |
1562 |
> |
if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) { |
1563 |
> |
mainLock = 0; |
1564 |
> |
synchronized (this) { notifyAll(); }; |
1565 |
> |
} |
1566 |
> |
} |
1567 |
> |
} |
1568 |
> |
else if (q.trySharedPush(task)) { |
1569 |
> |
signalWork(); |
1570 |
> |
return; |
1571 |
> |
} |
1572 |
> |
else if (m > 1) { // move to a different index |
1573 |
> |
r ^= r << 13; // same xorshift as WorkQueues |
1574 |
> |
r ^= r >>> 17; |
1575 |
> |
s.seed = r ^= r << 5; |
1576 |
> |
} |
1577 |
> |
else |
1578 |
> |
Thread.yield(); // yield if no alternatives |
1579 |
|
} |
903 |
– |
signalWork(); |
1580 |
|
} |
1581 |
|
|
906 |
– |
// (pollSubmission is defined below with exported methods) |
907 |
– |
|
1582 |
|
/** |
1583 |
< |
* Creates or doubles submissionQueue array. |
910 |
< |
* Basically identical to ForkJoinWorkerThread version. |
1583 |
> |
* Submits the given (non-null) task to the common pool, if possible. |
1584 |
|
*/ |
1585 |
< |
private void growSubmissionQueue() { |
1586 |
< |
ForkJoinTask<?>[] oldQ = submissionQueue; |
1587 |
< |
int size = oldQ != null ? oldQ.length << 1 : INITIAL_QUEUE_CAPACITY; |
1588 |
< |
if (size > MAXIMUM_QUEUE_CAPACITY) |
1589 |
< |
throw new RejectedExecutionException("Queue capacity exceeded"); |
917 |
< |
if (size < INITIAL_QUEUE_CAPACITY) |
918 |
< |
size = INITIAL_QUEUE_CAPACITY; |
919 |
< |
ForkJoinTask<?>[] q = submissionQueue = new ForkJoinTask<?>[size]; |
920 |
< |
int mask = size - 1; |
921 |
< |
int top = queueTop; |
922 |
< |
int oldMask; |
923 |
< |
if (oldQ != null && (oldMask = oldQ.length - 1) >= 0) { |
924 |
< |
for (int b = queueBase; b != top; ++b) { |
925 |
< |
long u = ((b & oldMask) << ASHIFT) + ABASE; |
926 |
< |
Object x = UNSAFE.getObjectVolatile(oldQ, u); |
927 |
< |
if (x != null && UNSAFE.compareAndSwapObject(oldQ, u, x, null)) |
928 |
< |
UNSAFE.putObjectVolatile |
929 |
< |
(q, ((b & mask) << ASHIFT) + ABASE, x); |
930 |
< |
} |
931 |
< |
} |
1585 |
> |
static void submitToCommonPool(ForkJoinTask<?> task) { |
1586 |
> |
ForkJoinPool p; |
1587 |
> |
if ((p = commonPool) == null) |
1588 |
> |
throw new RejectedExecutionException("Common Pool Unavailable"); |
1589 |
> |
p.doSubmit(task); |
1590 |
|
} |
1591 |
|
|
1592 |
< |
// Blocking support |
1592 |
> |
/** |
1593 |
> |
* Returns true if caller is (or may be) submitter to the common |
1594 |
> |
* pool, and not all workers are active, and there appear to be |
1595 |
> |
* tasks in the associated submission queue. |
1596 |
> |
*/ |
1597 |
> |
static boolean canHelpCommonPool() { |
1598 |
> |
ForkJoinPool p; WorkQueue[] ws; WorkQueue q; |
1599 |
> |
int k = submitters.get().seed & SQMASK; |
1600 |
> |
return ((p = commonPool) != null && |
1601 |
> |
(int)(p.ctl >> AC_SHIFT) < 0 && |
1602 |
> |
(ws = p.workQueues) != null && |
1603 |
> |
ws.length > (k &= p.submitMask) && |
1604 |
> |
(q = ws[k]) != null && |
1605 |
> |
q.top - q.base > 0); |
1606 |
> |
} |
1607 |
|
|
1608 |
|
/** |
1609 |
< |
* Tries to increment blockedCount, decrement active count |
1610 |
< |
* (sometimes implicitly) and possibly release or create a |
1611 |
< |
* compensating worker in preparation for blocking. Fails |
1612 |
< |
* on contention or termination. |
1609 |
> |
* Returns true if the given task was submitted to common pool |
1610 |
> |
* and has not yet commenced execution, and is available for |
1611 |
> |
* removal according to execution policies; if so removing the |
1612 |
> |
* submission from the pool. |
1613 |
|
* |
1614 |
< |
* @return true if the caller can block, else should recheck and retry |
1614 |
> |
* @param task the task |
1615 |
> |
* @return true if successful |
1616 |
|
*/ |
1617 |
< |
private boolean tryPreBlock() { |
1618 |
< |
int b = blockedCount; |
1619 |
< |
if (UNSAFE.compareAndSwapInt(this, blockedCountOffset, b, b + 1)) { |
1620 |
< |
int pc = parallelism; |
1621 |
< |
do { |
1622 |
< |
ForkJoinWorkerThread[] ws; ForkJoinWorkerThread w; |
1623 |
< |
int e, ac, tc, i; |
1624 |
< |
long c = ctl; |
1625 |
< |
int u = (int)(c >>> 32); |
1626 |
< |
if ((e = (int)c) < 0) { |
1627 |
< |
// skip -- terminating |
1628 |
< |
} |
1629 |
< |
else if ((ac = (u >> UAC_SHIFT)) <= 0 && e != 0 && |
1630 |
< |
(ws = workers) != null && |
1631 |
< |
(i = ~e & SMASK) < ws.length && |
1632 |
< |
(w = ws[i]) != null) { |
960 |
< |
long nc = ((long)(w.nextWait & E_MASK) | |
961 |
< |
(c & (AC_MASK|TC_MASK))); |
962 |
< |
if (w.eventCount == e && |
963 |
< |
UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) { |
964 |
< |
w.eventCount = (e + EC_UNIT) & E_MASK; |
965 |
< |
if (w.parked) |
966 |
< |
UNSAFE.unpark(w); |
967 |
< |
return true; // release an idle worker |
968 |
< |
} |
969 |
< |
} |
970 |
< |
else if ((tc = (short)(u >>> UTC_SHIFT)) >= 0 && ac + pc > 1) { |
971 |
< |
long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK); |
972 |
< |
if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) |
973 |
< |
return true; // no compensation needed |
974 |
< |
} |
975 |
< |
else if (tc + pc < MAX_ID) { |
976 |
< |
long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK); |
977 |
< |
if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) { |
978 |
< |
addWorker(); |
979 |
< |
return true; // create a replacement |
980 |
< |
} |
981 |
< |
} |
982 |
< |
// try to back out on any failure and let caller retry |
983 |
< |
} while (!UNSAFE.compareAndSwapInt(this, blockedCountOffset, |
984 |
< |
b = blockedCount, b - 1)); |
985 |
< |
} |
986 |
< |
return false; |
1617 |
> |
static boolean tryUnsubmitFromCommonPool(ForkJoinTask<?> task) { |
1618 |
> |
// Peek, looking for task and eligibility before |
1619 |
> |
// using trySharedUnpush to actually take it under lock |
1620 |
> |
ForkJoinPool p; WorkQueue[] ws; WorkQueue q; |
1621 |
> |
ForkJoinTask<?>[] a; int s; |
1622 |
> |
int k = submitters.get().seed & SQMASK; |
1623 |
> |
return ((p = commonPool) != null && |
1624 |
> |
(int)(p.ctl >> AC_SHIFT) < 0 && |
1625 |
> |
(ws = p.workQueues) != null && |
1626 |
> |
ws.length > (k &= p.submitMask) && |
1627 |
> |
(q = ws[k]) != null && |
1628 |
> |
(a = q.array) != null && |
1629 |
> |
(s = q.top - 1) - q.base >= 0 && |
1630 |
> |
s >= 0 && s < a.length && |
1631 |
> |
a[s] == task && |
1632 |
> |
q.trySharedUnpush(task)); |
1633 |
|
} |
1634 |
|
|
1635 |
|
/** |
1636 |
< |
* Decrements blockedCount and increments active count. |
1637 |
< |
*/ |
1638 |
< |
private void postBlock() { |
1639 |
< |
long c; |
1640 |
< |
do {} while (!UNSAFE.compareAndSwapLong(this, ctlOffset, // no mask |
1641 |
< |
c = ctl, c + AC_UNIT)); |
1642 |
< |
int b; |
1643 |
< |
do {} while (!UNSAFE.compareAndSwapInt(this, blockedCountOffset, |
1644 |
< |
b = blockedCount, b - 1)); |
1636 |
> |
* Tries to pop a task from common pool with given root |
1637 |
> |
*/ |
1638 |
> |
static ForkJoinTask<?> popCCFromCommonPool(CountedCompleter<?> root) { |
1639 |
> |
ForkJoinPool p; WorkQueue[] ws; WorkQueue q; |
1640 |
> |
ForkJoinTask<?> t; |
1641 |
> |
int k = submitters.get().seed & SQMASK; |
1642 |
> |
if (root != null && |
1643 |
> |
(p = commonPool) != null && |
1644 |
> |
(int)(p.ctl >> AC_SHIFT) < 0 && |
1645 |
> |
(ws = p.workQueues) != null && |
1646 |
> |
ws.length > (k &= p.submitMask) && |
1647 |
> |
(q = ws[k]) != null && q.top - q.base > 0 && |
1648 |
> |
root.status < 0 && |
1649 |
> |
(t = q.sharedPopCC(root)) != null) |
1650 |
> |
return t; |
1651 |
> |
return null; |
1652 |
|
} |
1653 |
|
|
1654 |
+ |
|
1655 |
+ |
// Maintaining ctl counts |
1656 |
+ |
|
1657 |
|
/** |
1658 |
< |
* Possibly blocks waiting for the given task to complete, or |
1003 |
< |
* cancels the task if terminating. Fails to wait if contended. |
1004 |
< |
* |
1005 |
< |
* @param joinMe the task |
1658 |
> |
* Increments active count; mainly called upon return from blocking. |
1659 |
|
*/ |
1660 |
< |
final void tryAwaitJoin(ForkJoinTask<?> joinMe) { |
1661 |
< |
Thread.interrupted(); // clear interrupts before checking termination |
1662 |
< |
if (joinMe.status >= 0) { |
1010 |
< |
if (tryPreBlock()) { |
1011 |
< |
joinMe.tryAwaitDone(0L); |
1012 |
< |
postBlock(); |
1013 |
< |
} |
1014 |
< |
else if ((ctl & STOP_BIT) != 0L) |
1015 |
< |
joinMe.cancelIgnoringExceptions(); |
1016 |
< |
} |
1660 |
> |
final void incrementActiveCount() { |
1661 |
> |
long c; |
1662 |
> |
do {} while (!U.compareAndSwapLong(this, CTL, c = ctl, c + AC_UNIT)); |
1663 |
|
} |
1664 |
|
|
1665 |
|
/** |
1666 |
< |
* Possibly blocks the given worker waiting for joinMe to |
1021 |
< |
* complete or timeout. |
1022 |
< |
* |
1023 |
< |
* @param joinMe the task |
1024 |
< |
* @param millis the wait time for underlying Object.wait |
1666 |
> |
* Tries to create one or activate one or more workers if too few are active. |
1667 |
|
*/ |
1668 |
< |
final void timedAwaitJoin(ForkJoinTask<?> joinMe, long nanos) { |
1669 |
< |
while (joinMe.status >= 0) { |
1670 |
< |
Thread.interrupted(); |
1671 |
< |
if ((ctl & STOP_BIT) != 0L) { |
1672 |
< |
joinMe.cancelIgnoringExceptions(); |
1673 |
< |
break; |
1674 |
< |
} |
1675 |
< |
if (tryPreBlock()) { |
1676 |
< |
long last = System.nanoTime(); |
1677 |
< |
while (joinMe.status >= 0) { |
1678 |
< |
long millis = TimeUnit.NANOSECONDS.toMillis(nanos); |
1679 |
< |
if (millis <= 0) |
1680 |
< |
break; |
1039 |
< |
joinMe.tryAwaitDone(millis); |
1040 |
< |
if (joinMe.status < 0) |
1041 |
< |
break; |
1042 |
< |
if ((ctl & STOP_BIT) != 0L) { |
1043 |
< |
joinMe.cancelIgnoringExceptions(); |
1668 |
> |
final void signalWork() { |
1669 |
> |
long c; int u; |
1670 |
> |
while ((u = (int)((c = ctl) >>> 32)) < 0) { // too few active |
1671 |
> |
WorkQueue[] ws = workQueues; int e, i; WorkQueue w; Thread p; |
1672 |
> |
if ((e = (int)c) > 0) { // at least one waiting |
1673 |
> |
if (ws != null && (i = e & SMASK) < ws.length && |
1674 |
> |
(w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) { |
1675 |
> |
long nc = (((long)(w.nextWait & E_MASK)) | |
1676 |
> |
((long)(u + UAC_UNIT) << 32)); |
1677 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
1678 |
> |
w.eventCount = (e + E_SEQ) & E_MASK; |
1679 |
> |
if ((p = w.parker) != null) |
1680 |
> |
U.unpark(p); // activate and release |
1681 |
|
break; |
1682 |
|
} |
1046 |
– |
long now = System.nanoTime(); |
1047 |
– |
nanos -= now - last; |
1048 |
– |
last = now; |
1683 |
|
} |
1684 |
< |
postBlock(); |
1685 |
< |
break; |
1684 |
> |
else |
1685 |
> |
break; |
1686 |
|
} |
1687 |
< |
} |
1688 |
< |
} |
1689 |
< |
|
1690 |
< |
/** |
1691 |
< |
* If necessary, compensates for blocker, and blocks. |
1692 |
< |
*/ |
1059 |
< |
private void awaitBlocker(ManagedBlocker blocker) |
1060 |
< |
throws InterruptedException { |
1061 |
< |
while (!blocker.isReleasable()) { |
1062 |
< |
if (tryPreBlock()) { |
1063 |
< |
try { |
1064 |
< |
do {} while (!blocker.isReleasable() && !blocker.block()); |
1065 |
< |
} finally { |
1066 |
< |
postBlock(); |
1687 |
> |
else if (e == 0 && (u & SHORT_SIGN) != 0) { // too few total |
1688 |
> |
long nc = (long)(((u + UTC_UNIT) & UTC_MASK) | |
1689 |
> |
((u + UAC_UNIT) & UAC_MASK)) << 32; |
1690 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
1691 |
> |
addWorker(); |
1692 |
> |
break; |
1693 |
|
} |
1068 |
– |
break; |
1694 |
|
} |
1695 |
+ |
else |
1696 |
+ |
break; |
1697 |
|
} |
1698 |
|
} |
1699 |
|
|
1700 |
< |
// Creating, registering and deregistring workers |
1700 |
> |
// Scanning for tasks |
1701 |
|
|
1702 |
|
/** |
1703 |
< |
* Tries to create and start a worker; minimally rolls back counts |
1077 |
< |
* on failure. |
1703 |
> |
* Top-level runloop for workers, called by ForkJoinWorkerThread.run. |
1704 |
|
*/ |
1705 |
< |
private void addWorker() { |
1706 |
< |
Throwable ex = null; |
1707 |
< |
ForkJoinWorkerThread t = null; |
1708 |
< |
try { |
1709 |
< |
t = factory.newThread(this); |
1710 |
< |
} catch (Throwable e) { |
1711 |
< |
ex = e; |
1712 |
< |
} |
1713 |
< |
if (t == null) { // null or exceptional factory return |
1714 |
< |
long c; // adjust counts |
1715 |
< |
do {} while (!UNSAFE.compareAndSwapLong |
1716 |
< |
(this, ctlOffset, c = ctl, |
1717 |
< |
(((c - AC_UNIT) & AC_MASK) | |
1718 |
< |
((c - TC_UNIT) & TC_MASK) | |
1719 |
< |
(c & ~(AC_MASK|TC_MASK))))); |
1720 |
< |
// Propagate exception if originating from an external caller |
1721 |
< |
if (!tryTerminate(false) && ex != null && |
1722 |
< |
!(Thread.currentThread() instanceof ForkJoinWorkerThread)) |
1723 |
< |
UNSAFE.throwException(ex); |
1705 |
> |
final void runWorker(WorkQueue w) { |
1706 |
> |
w.growArray(false); // initialize queue array in this thread |
1707 |
> |
do { w.runTask(scan(w)); } while (w.runState >= 0); |
1708 |
> |
} |
1709 |
> |
|
1710 |
> |
/** |
1711 |
> |
* Scans for and, if found, returns one task, else possibly |
1712 |
> |
* inactivates the worker. This method operates on single reads of |
1713 |
> |
* volatile state and is designed to be re-invoked continuously, |
1714 |
> |
* in part because it returns upon detecting inconsistencies, |
1715 |
> |
* contention, or state changes that indicate possible success on |
1716 |
> |
* re-invocation. |
1717 |
> |
* |
1718 |
> |
* The scan searches for tasks across a random permutation of |
1719 |
> |
* queues (starting at a random index and stepping by a random |
1720 |
> |
* relative prime, checking each at least once). The scan |
1721 |
> |
* terminates upon either finding a non-empty queue, or completing |
1722 |
> |
* the sweep. If the worker is not inactivated, it takes and |
1723 |
> |
* returns a task from this queue. On failure to find a task, we |
1724 |
> |
* take one of the following actions, after which the caller will |
1725 |
> |
* retry calling this method unless terminated. |
1726 |
> |
* |
1727 |
> |
* * If pool is terminating, terminate the worker. |
1728 |
> |
* |
1729 |
> |
* * If not a complete sweep, try to release a waiting worker. If |
1730 |
> |
* the scan terminated because the worker is inactivated, then the |
1731 |
> |
* released worker will often be the calling worker, and it can |
1732 |
> |
* succeed obtaining a task on the next call. Or maybe it is |
1733 |
> |
* another worker, but with same net effect. Releasing in other |
1734 |
> |
* cases as well ensures that we have enough workers running. |
1735 |
> |
* |
1736 |
> |
* * If not already enqueued, try to inactivate and enqueue the |
1737 |
> |
* worker on wait queue. Or, if inactivating has caused the pool |
1738 |
> |
* to be quiescent, relay to idleAwaitWork to check for |
1739 |
> |
* termination and possibly shrink pool. |
1740 |
> |
* |
1741 |
> |
* * If already inactive, and the caller has run a task since the |
1742 |
> |
* last empty scan, return (to allow rescan) unless others are |
1743 |
> |
* also inactivated. Field WorkQueue.rescans counts down on each |
1744 |
> |
* scan to ensure eventual inactivation and blocking. |
1745 |
> |
* |
1746 |
> |
* * If already enqueued and none of the above apply, park |
1747 |
> |
* awaiting signal, |
1748 |
> |
* |
1749 |
> |
* @param w the worker (via its WorkQueue) |
1750 |
> |
* @return a task or null if none found |
1751 |
> |
*/ |
1752 |
> |
private final ForkJoinTask<?> scan(WorkQueue w) { |
1753 |
> |
WorkQueue[] ws; // first update random seed |
1754 |
> |
int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5; |
1755 |
> |
int rs = runState, m; // volatile read order matters |
1756 |
> |
if ((ws = workQueues) != null && (m = ws.length - 1) > 0) { |
1757 |
> |
int ec = w.eventCount; // ec is negative if inactive |
1758 |
> |
int step = (r >>> 16) | 1; // relative prime |
1759 |
> |
for (int j = (m + 1) << 2; ; r += step) { |
1760 |
> |
WorkQueue q; ForkJoinTask<?> t; ForkJoinTask<?>[] a; int b; |
1761 |
> |
if ((q = ws[r & m]) != null && (b = q.base) - q.top < 0 && |
1762 |
> |
(a = q.array) != null) { // probably nonempty |
1763 |
> |
int i = (((a.length - 1) & b) << ASHIFT) + ABASE; |
1764 |
> |
t = (ForkJoinTask<?>)U.getObjectVolatile(a, i); |
1765 |
> |
if (q.base == b && ec >= 0 && t != null && |
1766 |
> |
U.compareAndSwapObject(a, i, t, null)) { |
1767 |
> |
if (q.top - (q.base = b + 1) > 0) |
1768 |
> |
signalWork(); // help pushes signal |
1769 |
> |
return t; |
1770 |
> |
} |
1771 |
> |
else if (ec < 0 || j <= m) { |
1772 |
> |
rs = 0; // mark scan as imcomplete |
1773 |
> |
break; // caller can retry after release |
1774 |
> |
} |
1775 |
> |
} |
1776 |
> |
if (--j < 0) |
1777 |
> |
break; |
1778 |
> |
} |
1779 |
> |
|
1780 |
> |
long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns; |
1781 |
> |
if (e < 0) // decode ctl on empty scan |
1782 |
> |
w.runState = -1; // pool is terminating |
1783 |
> |
else if (rs == 0 || rs != runState) { // incomplete scan |
1784 |
> |
WorkQueue v; Thread p; // try to release a waiter |
1785 |
> |
if (e > 0 && a < 0 && w.eventCount == ec && |
1786 |
> |
(v = ws[e & m]) != null && v.eventCount == (e | INT_SIGN)) { |
1787 |
> |
long nc = ((long)(v.nextWait & E_MASK) | |
1788 |
> |
((c + AC_UNIT) & (AC_MASK|TC_MASK))); |
1789 |
> |
if (ctl == c && U.compareAndSwapLong(this, CTL, c, nc)) { |
1790 |
> |
v.eventCount = (e + E_SEQ) & E_MASK; |
1791 |
> |
if ((p = v.parker) != null) |
1792 |
> |
U.unpark(p); |
1793 |
> |
} |
1794 |
> |
} |
1795 |
> |
} |
1796 |
> |
else if (ec >= 0) { // try to enqueue/inactivate |
1797 |
> |
long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK)); |
1798 |
> |
w.nextWait = e; |
1799 |
> |
w.eventCount = ec | INT_SIGN; // mark as inactive |
1800 |
> |
if (ctl != c || !U.compareAndSwapLong(this, CTL, c, nc)) |
1801 |
> |
w.eventCount = ec; // unmark on CAS failure |
1802 |
> |
else { |
1803 |
> |
if ((ns = w.nsteals) != 0) { |
1804 |
> |
w.nsteals = 0; // set rescans if ran task |
1805 |
> |
w.rescans = (a > 0) ? 0 : a + parallelism; |
1806 |
> |
w.totalSteals += ns; |
1807 |
> |
} |
1808 |
> |
if (a == 1 - parallelism) // quiescent |
1809 |
> |
idleAwaitWork(w, nc, c); |
1810 |
> |
} |
1811 |
> |
} |
1812 |
> |
else if (w.eventCount < 0) { // already queued |
1813 |
> |
int ac = a + parallelism; |
1814 |
> |
if ((nr = w.rescans) > 0) // continue rescanning |
1815 |
> |
w.rescans = (ac < nr) ? ac : nr - 1; |
1816 |
> |
else if (((w.seed >>> 16) & ac) == 0) { // randomize park |
1817 |
> |
Thread.interrupted(); // clear status |
1818 |
> |
Thread wt = Thread.currentThread(); |
1819 |
> |
U.putObject(wt, PARKBLOCKER, this); |
1820 |
> |
w.parker = wt; // emulate LockSupport.park |
1821 |
> |
if (w.eventCount < 0) // recheck |
1822 |
> |
U.park(false, 0L); |
1823 |
> |
w.parker = null; |
1824 |
> |
U.putObject(wt, PARKBLOCKER, null); |
1825 |
> |
} |
1826 |
> |
} |
1827 |
|
} |
1828 |
< |
else |
1100 |
< |
t.start(); |
1828 |
> |
return null; |
1829 |
|
} |
1830 |
|
|
1831 |
|
/** |
1832 |
< |
* Callback from ForkJoinWorkerThread constructor to assign a |
1833 |
< |
* public name |
1832 |
> |
* If inactivating worker w has caused the pool to become |
1833 |
> |
* quiescent, checks for pool termination, and, so long as this is |
1834 |
> |
* not the only worker, waits for event for up to a given |
1835 |
> |
* duration. On timeout, if ctl has not changed, terminates the |
1836 |
> |
* worker, which will in turn wake up another worker to possibly |
1837 |
> |
* repeat this process. |
1838 |
> |
* |
1839 |
> |
* @param w the calling worker |
1840 |
> |
* @param currentCtl the ctl value triggering possible quiescence |
1841 |
> |
* @param prevCtl the ctl value to restore if thread is terminated |
1842 |
|
*/ |
1843 |
< |
final String nextWorkerName() { |
1844 |
< |
for (int n;;) { |
1845 |
< |
if (UNSAFE.compareAndSwapInt(this, nextWorkerNumberOffset, |
1846 |
< |
n = nextWorkerNumber, ++n)) |
1847 |
< |
return workerNamePrefix + n; |
1843 |
> |
private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) { |
1844 |
> |
if (w.eventCount < 0 && !tryTerminate(false, false) && |
1845 |
> |
(int)prevCtl != 0 && !hasQueuedSubmissions() && ctl == currentCtl) { |
1846 |
> |
int dc = -(short)(currentCtl >>> TC_SHIFT); |
1847 |
> |
long parkTime = dc < 0 ? FAST_IDLE_TIMEOUT: (dc + 1) * IDLE_TIMEOUT; |
1848 |
> |
long deadline = System.nanoTime() + parkTime - 100000L; // 1ms slop |
1849 |
> |
Thread wt = Thread.currentThread(); |
1850 |
> |
while (ctl == currentCtl) { |
1851 |
> |
Thread.interrupted(); // timed variant of version in scan() |
1852 |
> |
U.putObject(wt, PARKBLOCKER, this); |
1853 |
> |
w.parker = wt; |
1854 |
> |
if (ctl == currentCtl) |
1855 |
> |
U.park(false, parkTime); |
1856 |
> |
w.parker = null; |
1857 |
> |
U.putObject(wt, PARKBLOCKER, null); |
1858 |
> |
if (ctl != currentCtl) |
1859 |
> |
break; |
1860 |
> |
if (deadline - System.nanoTime() <= 0L && |
1861 |
> |
U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) { |
1862 |
> |
w.eventCount = (w.eventCount + E_SEQ) | E_MASK; |
1863 |
> |
w.runState = -1; // shrink |
1864 |
> |
break; |
1865 |
> |
} |
1866 |
> |
} |
1867 |
|
} |
1868 |
|
} |
1869 |
|
|
1870 |
|
/** |
1871 |
< |
* Callback from ForkJoinWorkerThread constructor to |
1872 |
< |
* determine its poolIndex and record in workers array. |
1873 |
< |
* |
1874 |
< |
* @param w the worker |
1875 |
< |
* @return the worker's pool index |
1876 |
< |
*/ |
1877 |
< |
final int registerWorker(ForkJoinWorkerThread w) { |
1878 |
< |
/* |
1879 |
< |
* In the typical case, a new worker acquires the lock, uses |
1880 |
< |
* next available index and returns quickly. Since we should |
1881 |
< |
* not block callers (ultimately from signalWork or |
1882 |
< |
* tryPreBlock) waiting for the lock needed to do this, we |
1883 |
< |
* instead help release other workers while waiting for the |
1884 |
< |
* lock. |
1885 |
< |
*/ |
1886 |
< |
for (int g;;) { |
1887 |
< |
ForkJoinWorkerThread[] ws; |
1888 |
< |
if (((g = scanGuard) & SG_UNIT) == 0 && |
1889 |
< |
UNSAFE.compareAndSwapInt(this, scanGuardOffset, |
1890 |
< |
g, g | SG_UNIT)) { |
1891 |
< |
int k = nextWorkerIndex; |
1892 |
< |
try { |
1893 |
< |
if ((ws = workers) != null) { // ignore on shutdown |
1894 |
< |
int n = ws.length; |
1895 |
< |
if (k < 0 || k >= n || ws[k] != null) { |
1896 |
< |
for (k = 0; k < n && ws[k] != null; ++k) |
1897 |
< |
; |
1898 |
< |
if (k == n) |
1899 |
< |
ws = workers = Arrays.copyOf(ws, n << 1); |
1871 |
> |
* Tries to locate and execute tasks for a stealer of the given |
1872 |
> |
* task, or in turn one of its stealers, Traces currentSteal -> |
1873 |
> |
* currentJoin links looking for a thread working on a descendant |
1874 |
> |
* of the given task and with a non-empty queue to steal back and |
1875 |
> |
* execute tasks from. The first call to this method upon a |
1876 |
> |
* waiting join will often entail scanning/search, (which is OK |
1877 |
> |
* because the joiner has nothing better to do), but this method |
1878 |
> |
* leaves hints in workers to speed up subsequent calls. The |
1879 |
> |
* implementation is very branchy to cope with potential |
1880 |
> |
* inconsistencies or loops encountering chains that are stale, |
1881 |
> |
* unknown, or so long that they are likely cyclic. |
1882 |
> |
* |
1883 |
> |
* @param joiner the joining worker |
1884 |
> |
* @param task the task to join |
1885 |
> |
* @return 0 if no progress can be made, negative if task |
1886 |
> |
* known complete, else positive |
1887 |
> |
*/ |
1888 |
> |
private int tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) { |
1889 |
> |
int stat = 0, steps = 0; // bound to avoid cycles |
1890 |
> |
if (joiner != null && task != null) { // hoist null checks |
1891 |
> |
restart: for (;;) { |
1892 |
> |
ForkJoinTask<?> subtask = task; // current target |
1893 |
> |
for (WorkQueue j = joiner, v;;) { // v is stealer of subtask |
1894 |
> |
WorkQueue[] ws; int m, s, h; |
1895 |
> |
if ((s = task.status) < 0) { |
1896 |
> |
stat = s; |
1897 |
> |
break restart; |
1898 |
> |
} |
1899 |
> |
if ((ws = workQueues) == null || (m = ws.length - 1) <= 0) |
1900 |
> |
break restart; // shutting down |
1901 |
> |
if ((v = ws[h = (j.stealHint | 1) & m]) == null || |
1902 |
> |
v.currentSteal != subtask) { |
1903 |
> |
for (int origin = h;;) { // find stealer |
1904 |
> |
if (((h = (h + 2) & m) & 15) == 1 && |
1905 |
> |
(subtask.status < 0 || j.currentJoin != subtask)) |
1906 |
> |
continue restart; // occasional staleness check |
1907 |
> |
if ((v = ws[h]) != null && |
1908 |
> |
v.currentSteal == subtask) { |
1909 |
> |
j.stealHint = h; // save hint |
1910 |
> |
break; |
1911 |
> |
} |
1912 |
> |
if (h == origin) |
1913 |
> |
break restart; // cannot find stealer |
1914 |
|
} |
1146 |
– |
ws[k] = w; |
1147 |
– |
nextWorkerIndex = k + 1; |
1148 |
– |
int m = g & SMASK; |
1149 |
– |
g = (k > m) ? ((m << 1) + 1) & SMASK : g + (SG_UNIT<<1); |
1915 |
|
} |
1916 |
< |
} finally { |
1917 |
< |
scanGuard = g; |
1918 |
< |
} |
1919 |
< |
return k; |
1920 |
< |
} |
1921 |
< |
else if ((ws = workers) != null) { // help release others |
1922 |
< |
for (ForkJoinWorkerThread u : ws) { |
1923 |
< |
if (u != null && u.queueBase != u.queueTop) { |
1924 |
< |
if (tryReleaseWaiter()) |
1925 |
< |
break; |
1916 |
> |
for (;;) { // help stealer or descend to its stealer |
1917 |
> |
ForkJoinTask[] a; int b; |
1918 |
> |
if (subtask.status < 0) // surround probes with |
1919 |
> |
continue restart; // consistency checks |
1920 |
> |
if ((b = v.base) - v.top < 0 && (a = v.array) != null) { |
1921 |
> |
int i = (((a.length - 1) & b) << ASHIFT) + ABASE; |
1922 |
> |
ForkJoinTask<?> t = |
1923 |
> |
(ForkJoinTask<?>)U.getObjectVolatile(a, i); |
1924 |
> |
if (subtask.status < 0 || j.currentJoin != subtask || |
1925 |
> |
v.currentSteal != subtask) |
1926 |
> |
continue restart; // stale |
1927 |
> |
stat = 1; // apparent progress |
1928 |
> |
if (t != null && v.base == b && |
1929 |
> |
U.compareAndSwapObject(a, i, t, null)) { |
1930 |
> |
v.base = b + 1; // help stealer |
1931 |
> |
joiner.runSubtask(t); |
1932 |
> |
} |
1933 |
> |
else if (v.base == b && ++steps == MAX_HELP) |
1934 |
> |
break restart; // v apparently stalled |
1935 |
> |
} |
1936 |
> |
else { // empty -- try to descend |
1937 |
> |
ForkJoinTask<?> next = v.currentJoin; |
1938 |
> |
if (subtask.status < 0 || j.currentJoin != subtask || |
1939 |
> |
v.currentSteal != subtask) |
1940 |
> |
continue restart; // stale |
1941 |
> |
else if (next == null || ++steps == MAX_HELP) |
1942 |
> |
break restart; // dead-end or maybe cyclic |
1943 |
> |
else { |
1944 |
> |
subtask = next; |
1945 |
> |
j = v; |
1946 |
> |
break; |
1947 |
> |
} |
1948 |
> |
} |
1949 |
|
} |
1950 |
|
} |
1951 |
|
} |
1952 |
|
} |
1953 |
+ |
return stat; |
1954 |
|
} |
1955 |
|
|
1956 |
|
/** |
1957 |
< |
* Final callback from terminating worker. Removes record of |
1169 |
< |
* worker from array, and adjusts counts. If pool is shutting |
1170 |
< |
* down, tries to complete termination. |
1957 |
> |
* If task is at base of some steal queue, steals and executes it. |
1958 |
|
* |
1959 |
< |
* @param w the worker |
1959 |
> |
* @param joiner the joining worker |
1960 |
> |
* @param task the task |
1961 |
|
*/ |
1962 |
< |
final void deregisterWorker(ForkJoinWorkerThread w, Throwable ex) { |
1963 |
< |
int idx = w.poolIndex; |
1964 |
< |
int sc = w.stealCount; |
1965 |
< |
int steps = 0; |
1966 |
< |
// Remove from array, adjust worker counts and collect steal count. |
1967 |
< |
// We can intermix failed removes or adjusts with steal updates |
1968 |
< |
do { |
1969 |
< |
long s, c; |
1970 |
< |
int g; |
1971 |
< |
if (steps == 0 && ((g = scanGuard) & SG_UNIT) == 0 && |
1184 |
< |
UNSAFE.compareAndSwapInt(this, scanGuardOffset, |
1185 |
< |
g, g |= SG_UNIT)) { |
1186 |
< |
ForkJoinWorkerThread[] ws = workers; |
1187 |
< |
if (ws != null && idx >= 0 && |
1188 |
< |
idx < ws.length && ws[idx] == w) |
1189 |
< |
ws[idx] = null; // verify |
1190 |
< |
nextWorkerIndex = idx; |
1191 |
< |
scanGuard = g + SG_UNIT; |
1192 |
< |
steps = 1; |
1193 |
< |
} |
1194 |
< |
if (steps == 1 && |
1195 |
< |
UNSAFE.compareAndSwapLong(this, ctlOffset, c = ctl, |
1196 |
< |
(((c - AC_UNIT) & AC_MASK) | |
1197 |
< |
((c - TC_UNIT) & TC_MASK) | |
1198 |
< |
(c & ~(AC_MASK|TC_MASK))))) |
1199 |
< |
steps = 2; |
1200 |
< |
if (sc != 0 && |
1201 |
< |
UNSAFE.compareAndSwapLong(this, stealCountOffset, |
1202 |
< |
s = stealCount, s + sc)) |
1203 |
< |
sc = 0; |
1204 |
< |
} while (steps != 2 || sc != 0); |
1205 |
< |
if (!tryTerminate(false)) { |
1206 |
< |
if (ex != null) // possibly replace if died abnormally |
1207 |
< |
signalWork(); |
1208 |
< |
else |
1209 |
< |
tryReleaseWaiter(); |
1962 |
> |
private void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) { |
1963 |
> |
WorkQueue[] ws; |
1964 |
> |
if ((ws = workQueues) != null) { |
1965 |
> |
for (int j = 1; j < ws.length && task.status >= 0; j += 2) { |
1966 |
> |
WorkQueue q = ws[j]; |
1967 |
> |
if (q != null && q.pollFor(task)) { |
1968 |
> |
joiner.runSubtask(task); |
1969 |
> |
break; |
1970 |
> |
} |
1971 |
> |
} |
1972 |
|
} |
1973 |
|
} |
1974 |
|
|
1213 |
– |
// Shutdown and termination |
1214 |
– |
|
1975 |
|
/** |
1976 |
< |
* Possibly initiates and/or completes termination. |
1976 |
> |
* Tries to decrement active count (sometimes implicitly) and |
1977 |
> |
* possibly release or create a compensating worker in preparation |
1978 |
> |
* for blocking. Fails on contention or termination. Otherwise, |
1979 |
> |
* adds a new thread if no idle workers are available and either |
1980 |
> |
* pool would become completely starved or: (at least half |
1981 |
> |
* starved, and fewer than 50% spares exist, and there is at least |
1982 |
> |
* one task apparently available). Even though the availability |
1983 |
> |
* check requires a full scan, it is worthwhile in reducing false |
1984 |
> |
* alarms. |
1985 |
|
* |
1986 |
< |
* @param now if true, unconditionally terminate, else only |
1987 |
< |
* if shutdown and empty queue and no active workers |
1988 |
< |
* @return true if now terminating or terminated |
1986 |
> |
* @param task if non-null, a task being waited for |
1987 |
> |
* @param blocker if non-null, a blocker being waited for |
1988 |
> |
* @return true if the caller can block, else should recheck and retry |
1989 |
|
*/ |
1990 |
< |
private boolean tryTerminate(boolean now) { |
1991 |
< |
long c; |
1992 |
< |
while (((c = ctl) & STOP_BIT) == 0) { |
1993 |
< |
if (!now) { |
1994 |
< |
if ((int)(c >> AC_SHIFT) != -parallelism) |
1995 |
< |
return false; |
1996 |
< |
if (!shutdown || blockedCount != 0 || quiescerCount != 0 || |
1997 |
< |
queueBase != queueTop) { |
1998 |
< |
if (ctl == c) // staleness check |
1999 |
< |
return false; |
2000 |
< |
continue; |
1990 |
> |
final boolean tryCompensate(ForkJoinTask<?> task, ManagedBlocker blocker) { |
1991 |
> |
int pc = parallelism, e; |
1992 |
> |
long c = ctl; |
1993 |
> |
WorkQueue[] ws = workQueues; |
1994 |
> |
if ((e = (int)c) >= 0 && ws != null) { |
1995 |
> |
int u, a, ac, hc; |
1996 |
> |
int tc = (short)((u = (int)(c >>> 32)) >>> UTC_SHIFT) + pc; |
1997 |
> |
boolean replace = false; |
1998 |
> |
if ((a = u >> UAC_SHIFT) <= 0) { |
1999 |
> |
if ((ac = a + pc) <= 1) |
2000 |
> |
replace = true; |
2001 |
> |
else if ((e > 0 || (task != null && |
2002 |
> |
ac <= (hc = pc >>> 1) && tc < pc + hc))) { |
2003 |
> |
WorkQueue w; |
2004 |
> |
for (int j = 0; j < ws.length; ++j) { |
2005 |
> |
if ((w = ws[j]) != null && !w.isEmpty()) { |
2006 |
> |
replace = true; |
2007 |
> |
break; // in compensation range and tasks available |
2008 |
> |
} |
2009 |
> |
} |
2010 |
|
} |
2011 |
|
} |
2012 |
< |
if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, c | STOP_BIT)) |
2013 |
< |
startTerminating(); |
2014 |
< |
} |
2015 |
< |
if ((short)(c >>> TC_SHIFT) == -parallelism) { // signal when 0 workers |
2016 |
< |
final ReentrantLock lock = this.submissionLock; |
2017 |
< |
lock.lock(); |
2018 |
< |
try { |
2019 |
< |
termination.signalAll(); |
2020 |
< |
} finally { |
2021 |
< |
lock.unlock(); |
2012 |
> |
if ((task == null || task.status >= 0) && // recheck need to block |
2013 |
> |
(blocker == null || !blocker.isReleasable()) && ctl == c) { |
2014 |
> |
if (!replace) { // no compensation |
2015 |
> |
long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK); |
2016 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) |
2017 |
> |
return true; |
2018 |
> |
} |
2019 |
> |
else if (e != 0) { // release an idle worker |
2020 |
> |
WorkQueue w; Thread p; int i; |
2021 |
> |
if ((i = e & SMASK) < ws.length && (w = ws[i]) != null) { |
2022 |
> |
long nc = ((long)(w.nextWait & E_MASK) | |
2023 |
> |
(c & (AC_MASK|TC_MASK))); |
2024 |
> |
if (w.eventCount == (e | INT_SIGN) && |
2025 |
> |
U.compareAndSwapLong(this, CTL, c, nc)) { |
2026 |
> |
w.eventCount = (e + E_SEQ) & E_MASK; |
2027 |
> |
if ((p = w.parker) != null) |
2028 |
> |
U.unpark(p); |
2029 |
> |
return true; |
2030 |
> |
} |
2031 |
> |
} |
2032 |
> |
} |
2033 |
> |
else if (tc < MAX_CAP) { // create replacement |
2034 |
> |
long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK); |
2035 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
2036 |
> |
addWorker(); |
2037 |
> |
return true; |
2038 |
> |
} |
2039 |
> |
} |
2040 |
|
} |
2041 |
|
} |
2042 |
< |
return true; |
2042 |
> |
return false; |
2043 |
|
} |
2044 |
|
|
2045 |
|
/** |
2046 |
< |
* Runs up to three passes through workers: (0) Setting |
2047 |
< |
* termination status for each worker, followed by wakeups up to |
2048 |
< |
* queued workers; (1) helping cancel tasks; (2) interrupting |
2049 |
< |
* lagging threads (likely in external tasks, but possibly also |
2050 |
< |
* blocked in joins). Each pass repeats previous steps because of |
2051 |
< |
* potential lagging thread creation. |
2052 |
< |
*/ |
2053 |
< |
private void startTerminating() { |
2054 |
< |
cancelSubmissions(); |
2055 |
< |
for (int pass = 0; pass < 3; ++pass) { |
2056 |
< |
ForkJoinWorkerThread[] ws = workers; |
2057 |
< |
if (ws != null) { |
2058 |
< |
for (ForkJoinWorkerThread w : ws) { |
2059 |
< |
if (w != null) { |
2060 |
< |
w.terminate = true; |
2061 |
< |
if (pass > 0) { |
2062 |
< |
w.cancelTasks(); |
2063 |
< |
if (pass > 1 && !w.isInterrupted()) { |
2064 |
< |
try { |
2065 |
< |
w.interrupt(); |
2066 |
< |
} catch (SecurityException ignore) { |
2046 |
> |
* Helps and/or blocks until the given task is done. |
2047 |
> |
* |
2048 |
> |
* @param joiner the joining worker |
2049 |
> |
* @param task the task |
2050 |
> |
* @return task status on exit |
2051 |
> |
*/ |
2052 |
> |
final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) { |
2053 |
> |
int s; |
2054 |
> |
if ((s = task.status) >= 0) { |
2055 |
> |
ForkJoinTask<?> prevJoin = joiner.currentJoin; |
2056 |
> |
joiner.currentJoin = task; |
2057 |
> |
long startTime = 0L; |
2058 |
> |
for (int k = 0;;) { |
2059 |
> |
if ((s = (joiner.isEmpty() ? // try to help |
2060 |
> |
tryHelpStealer(joiner, task) : |
2061 |
> |
joiner.tryRemoveAndExec(task))) == 0 && |
2062 |
> |
(s = task.status) >= 0) { |
2063 |
> |
if (k == 0) { |
2064 |
> |
startTime = System.nanoTime(); |
2065 |
> |
tryPollForAndExec(joiner, task); // check uncommon case |
2066 |
> |
} |
2067 |
> |
else if ((k & (MAX_HELP - 1)) == 0 && |
2068 |
> |
System.nanoTime() - startTime >= |
2069 |
> |
COMPENSATION_DELAY && |
2070 |
> |
tryCompensate(task, null)) { |
2071 |
> |
if (task.trySetSignal()) { |
2072 |
> |
synchronized (task) { |
2073 |
> |
if (task.status >= 0) { |
2074 |
> |
try { // see ForkJoinTask |
2075 |
> |
task.wait(); // for explanation |
2076 |
> |
} catch (InterruptedException ie) { |
2077 |
> |
} |
2078 |
|
} |
2079 |
+ |
else |
2080 |
+ |
task.notifyAll(); |
2081 |
|
} |
2082 |
|
} |
2083 |
+ |
long c; // re-activate |
2084 |
+ |
do {} while (!U.compareAndSwapLong |
2085 |
+ |
(this, CTL, c = ctl, c + AC_UNIT)); |
2086 |
|
} |
2087 |
|
} |
2088 |
< |
terminateWaiters(); |
2088 |
> |
if (s < 0 || (s = task.status) < 0) { |
2089 |
> |
joiner.currentJoin = prevJoin; |
2090 |
> |
break; |
2091 |
> |
} |
2092 |
> |
else if ((k++ & (MAX_HELP - 1)) == MAX_HELP >>> 1) |
2093 |
> |
Thread.yield(); // for politeness |
2094 |
|
} |
2095 |
|
} |
2096 |
+ |
return s; |
2097 |
|
} |
2098 |
|
|
2099 |
|
/** |
2100 |
< |
* Polls and cancels all submissions. Called only during termination. |
2100 |
> |
* Stripped-down variant of awaitJoin used by timed joins. Tries |
2101 |
> |
* to help join only while there is continuous progress. (Caller |
2102 |
> |
* will then enter a timed wait.) |
2103 |
> |
* |
2104 |
> |
* @param joiner the joining worker |
2105 |
> |
* @param task the task |
2106 |
> |
* @return task status on exit |
2107 |
|
*/ |
2108 |
< |
private void cancelSubmissions() { |
2109 |
< |
while (queueBase != queueTop) { |
2110 |
< |
ForkJoinTask<?> task = pollSubmission(); |
2111 |
< |
if (task != null) { |
2112 |
< |
try { |
2113 |
< |
task.cancel(false); |
2114 |
< |
} catch (Throwable ignore) { |
2108 |
> |
final int helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) { |
2109 |
> |
int s; |
2110 |
> |
while ((s = task.status) >= 0 && |
2111 |
> |
(joiner.isEmpty() ? |
2112 |
> |
tryHelpStealer(joiner, task) : |
2113 |
> |
joiner.tryRemoveAndExec(task)) != 0) |
2114 |
> |
; |
2115 |
> |
return s; |
2116 |
> |
} |
2117 |
> |
|
2118 |
> |
/** |
2119 |
> |
* Returns a (probably) non-empty steal queue, if one is found |
2120 |
> |
* during a random, then cyclic scan, else null. This method must |
2121 |
> |
* be retried by caller if, by the time it tries to use the queue, |
2122 |
> |
* it is empty. |
2123 |
> |
*/ |
2124 |
> |
private WorkQueue findNonEmptyStealQueue(WorkQueue w) { |
2125 |
> |
// Similar to loop in scan(), but ignoring submissions |
2126 |
> |
int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5; |
2127 |
> |
int step = (r >>> 16) | 1; |
2128 |
> |
for (WorkQueue[] ws;;) { |
2129 |
> |
int rs = runState, m; |
2130 |
> |
if ((ws = workQueues) == null || (m = ws.length - 1) < 1) |
2131 |
> |
return null; |
2132 |
> |
for (int j = (m + 1) << 2; ; r += step) { |
2133 |
> |
WorkQueue q = ws[((r << 1) | 1) & m]; |
2134 |
> |
if (q != null && !q.isEmpty()) |
2135 |
> |
return q; |
2136 |
> |
else if (--j < 0) { |
2137 |
> |
if (runState == rs) |
2138 |
> |
return null; |
2139 |
> |
break; |
2140 |
|
} |
2141 |
|
} |
2142 |
|
} |
2143 |
|
} |
2144 |
|
|
2145 |
|
/** |
2146 |
< |
* Tries to set the termination status of waiting workers, and |
2147 |
< |
* then wakes them up (after which they will terminate). |
2148 |
< |
*/ |
2149 |
< |
private void terminateWaiters() { |
2150 |
< |
ForkJoinWorkerThread[] ws = workers; |
2151 |
< |
if (ws != null) { |
2152 |
< |
ForkJoinWorkerThread w; long c; int i, e; |
2153 |
< |
int n = ws.length; |
2154 |
< |
while ((i = ~(e = (int)(c = ctl)) & SMASK) < n && |
2155 |
< |
(w = ws[i]) != null && w.eventCount == (e & E_MASK)) { |
2156 |
< |
if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, |
2157 |
< |
(long)(w.nextWait & E_MASK) | |
2158 |
< |
((c + AC_UNIT) & AC_MASK) | |
2159 |
< |
(c & (TC_MASK|STOP_BIT)))) { |
2160 |
< |
w.terminate = true; |
2161 |
< |
w.eventCount = e + EC_UNIT; |
2162 |
< |
if (w.parked) |
2163 |
< |
UNSAFE.unpark(w); |
2146 |
> |
* Runs tasks until {@code isQuiescent()}. We piggyback on |
2147 |
> |
* active count ctl maintenance, but rather than blocking |
2148 |
> |
* when tasks cannot be found, we rescan until all others cannot |
2149 |
> |
* find tasks either. |
2150 |
> |
*/ |
2151 |
> |
final void helpQuiescePool(WorkQueue w) { |
2152 |
> |
for (boolean active = true;;) { |
2153 |
> |
ForkJoinTask<?> localTask; // exhaust local queue |
2154 |
> |
while ((localTask = w.nextLocalTask()) != null) |
2155 |
> |
localTask.doExec(); |
2156 |
> |
WorkQueue q = findNonEmptyStealQueue(w); |
2157 |
> |
if (q != null) { |
2158 |
> |
ForkJoinTask<?> t; int b; |
2159 |
> |
if (!active) { // re-establish active count |
2160 |
> |
long c; |
2161 |
> |
active = true; |
2162 |
> |
do {} while (!U.compareAndSwapLong |
2163 |
> |
(this, CTL, c = ctl, c + AC_UNIT)); |
2164 |
> |
} |
2165 |
> |
if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null) |
2166 |
> |
w.runSubtask(t); |
2167 |
> |
} |
2168 |
> |
else { |
2169 |
> |
long c; |
2170 |
> |
if (active) { // decrement active count without queuing |
2171 |
> |
active = false; |
2172 |
> |
do {} while (!U.compareAndSwapLong |
2173 |
> |
(this, CTL, c = ctl, c -= AC_UNIT)); |
2174 |
> |
} |
2175 |
> |
else |
2176 |
> |
c = ctl; // re-increment on exit |
2177 |
> |
if ((int)(c >> AC_SHIFT) + parallelism == 0) { |
2178 |
> |
do {} while (!U.compareAndSwapLong |
2179 |
> |
(this, CTL, c = ctl, c + AC_UNIT)); |
2180 |
> |
break; |
2181 |
|
} |
2182 |
|
} |
2183 |
|
} |
2184 |
|
} |
2185 |
|
|
1321 |
– |
// misc ForkJoinWorkerThread support |
1322 |
– |
|
2186 |
|
/** |
2187 |
< |
* Increments or decrements quiescerCount. Needed only to prevent |
1325 |
< |
* triggering shutdown if a worker is transiently inactive while |
1326 |
< |
* checking quiescence. |
1327 |
< |
* |
1328 |
< |
* @param delta 1 for increment, -1 for decrement |
2187 |
> |
* Restricted version of helpQuiescePool for non-FJ callers |
2188 |
|
*/ |
2189 |
< |
final void addQuiescerCount(int delta) { |
2190 |
< |
int c; |
2191 |
< |
do {} while (!UNSAFE.compareAndSwapInt(this, quiescerCountOffset, |
2192 |
< |
c = quiescerCount, c + delta)); |
2189 |
> |
static void externalHelpQuiescePool() { |
2190 |
> |
ForkJoinPool p; WorkQueue[] ws; WorkQueue q, sq; |
2191 |
> |
ForkJoinTask<?>[] a; int b; |
2192 |
> |
ForkJoinTask<?> t = null; |
2193 |
> |
int k = submitters.get().seed & SQMASK; |
2194 |
> |
if ((p = commonPool) != null && |
2195 |
> |
(int)(p.ctl >> AC_SHIFT) < 0 && |
2196 |
> |
(ws = p.workQueues) != null && |
2197 |
> |
ws.length > (k &= p.submitMask) && |
2198 |
> |
(q = ws[k]) != null) { |
2199 |
> |
while (q.top - q.base > 0) { |
2200 |
> |
if ((t = q.sharedPop()) != null) |
2201 |
> |
break; |
2202 |
> |
} |
2203 |
> |
if (t == null && (sq = p.findNonEmptyStealQueue(q)) != null && |
2204 |
> |
(b = sq.base) - sq.top < 0) |
2205 |
> |
t = sq.pollAt(b); |
2206 |
> |
if (t != null) |
2207 |
> |
t.doExec(); |
2208 |
> |
} |
2209 |
|
} |
2210 |
|
|
2211 |
|
/** |
2212 |
< |
* Directly increments or decrements active count without queuing. |
1338 |
< |
* This method is used to transiently assert inactivation while |
1339 |
< |
* checking quiescence. |
2212 |
> |
* Gets and removes a local or stolen task for the given worker. |
2213 |
|
* |
2214 |
< |
* @param delta 1 for increment, -1 for decrement |
2214 |
> |
* @return a task, if available |
2215 |
|
*/ |
2216 |
< |
final void addActiveCount(int delta) { |
2217 |
< |
long d = delta < 0 ? -AC_UNIT : AC_UNIT; |
2218 |
< |
long c; |
2219 |
< |
do {} while (!UNSAFE.compareAndSwapLong(this, ctlOffset, c = ctl, |
2220 |
< |
((c + d) & AC_MASK) | |
2221 |
< |
(c & ~AC_MASK))); |
2216 |
> |
final ForkJoinTask<?> nextTaskFor(WorkQueue w) { |
2217 |
> |
for (ForkJoinTask<?> t;;) { |
2218 |
> |
WorkQueue q; int b; |
2219 |
> |
if ((t = w.nextLocalTask()) != null) |
2220 |
> |
return t; |
2221 |
> |
if ((q = findNonEmptyStealQueue(w)) == null) |
2222 |
> |
return null; |
2223 |
> |
if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null) |
2224 |
> |
return t; |
2225 |
> |
} |
2226 |
|
} |
2227 |
|
|
2228 |
|
/** |
2229 |
|
* Returns the approximate (non-atomic) number of idle threads per |
2230 |
< |
* active thread. |
2230 |
> |
* active thread to offset steal queue size for method |
2231 |
> |
* ForkJoinTask.getSurplusQueuedTaskCount(). |
2232 |
|
*/ |
2233 |
|
final int idlePerActive() { |
2234 |
|
// Approximate at powers of two for small values, saturate past 4 |
2241 |
|
8); |
2242 |
|
} |
2243 |
|
|
2244 |
+ |
/** |
2245 |
+ |
* Returns approximate submission queue length for the given caller |
2246 |
+ |
*/ |
2247 |
+ |
static int getEstimatedSubmitterQueueLength() { |
2248 |
+ |
ForkJoinPool p; WorkQueue[] ws; WorkQueue q; |
2249 |
+ |
int k = submitters.get().seed & SQMASK; |
2250 |
+ |
return ((p = commonPool) != null && |
2251 |
+ |
p.runState >= 0 && |
2252 |
+ |
(ws = p.workQueues) != null && |
2253 |
+ |
ws.length > (k &= p.submitMask) && |
2254 |
+ |
(q = ws[k]) != null) ? |
2255 |
+ |
q.queueSize() : 0; |
2256 |
+ |
} |
2257 |
+ |
|
2258 |
+ |
// Termination |
2259 |
+ |
|
2260 |
+ |
/** |
2261 |
+ |
* Possibly initiates and/or completes termination. The caller |
2262 |
+ |
* triggering termination runs three passes through workQueues: |
2263 |
+ |
* (0) Setting termination status, followed by wakeups of queued |
2264 |
+ |
* workers; (1) cancelling all tasks; (2) interrupting lagging |
2265 |
+ |
* threads (likely in external tasks, but possibly also blocked in |
2266 |
+ |
* joins). Each pass repeats previous steps because of potential |
2267 |
+ |
* lagging thread creation. |
2268 |
+ |
* |
2269 |
+ |
* @param now if true, unconditionally terminate, else only |
2270 |
+ |
* if no work and no active workers |
2271 |
+ |
* @param enable if true, enable shutdown when next possible |
2272 |
+ |
* @return true if now terminating or terminated |
2273 |
+ |
*/ |
2274 |
+ |
private boolean tryTerminate(boolean now, boolean enable) { |
2275 |
+ |
for (long c;;) { |
2276 |
+ |
if (((c = ctl) & STOP_BIT) != 0) { // already terminating |
2277 |
+ |
if ((short)(c >>> TC_SHIFT) == -parallelism) { |
2278 |
+ |
synchronized (this) { |
2279 |
+ |
notifyAll(); // signal when 0 workers |
2280 |
+ |
} |
2281 |
+ |
} |
2282 |
+ |
return true; |
2283 |
+ |
} |
2284 |
+ |
if (runState >= 0) { // not yet enabled |
2285 |
+ |
if (!enable) |
2286 |
+ |
return false; |
2287 |
+ |
while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1)) |
2288 |
+ |
tryAwaitMainLock(); |
2289 |
+ |
try { |
2290 |
+ |
runState |= SHUTDOWN; |
2291 |
+ |
} finally { |
2292 |
+ |
if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) { |
2293 |
+ |
mainLock = 0; |
2294 |
+ |
synchronized (this) { notifyAll(); }; |
2295 |
+ |
} |
2296 |
+ |
} |
2297 |
+ |
} |
2298 |
+ |
if (!now) { // check if idle & no tasks |
2299 |
+ |
if ((int)(c >> AC_SHIFT) != -parallelism || |
2300 |
+ |
hasQueuedSubmissions()) |
2301 |
+ |
return false; |
2302 |
+ |
// Check for unqueued inactive workers. One pass suffices. |
2303 |
+ |
WorkQueue[] ws = workQueues; WorkQueue w; |
2304 |
+ |
if (ws != null) { |
2305 |
+ |
for (int i = 1; i < ws.length; i += 2) { |
2306 |
+ |
if ((w = ws[i]) != null && w.eventCount >= 0) |
2307 |
+ |
return false; |
2308 |
+ |
} |
2309 |
+ |
} |
2310 |
+ |
} |
2311 |
+ |
if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) { |
2312 |
+ |
for (int pass = 0; pass < 3; ++pass) { |
2313 |
+ |
WorkQueue[] ws = workQueues; |
2314 |
+ |
if (ws != null) { |
2315 |
+ |
WorkQueue w; |
2316 |
+ |
int n = ws.length; |
2317 |
+ |
for (int i = 0; i < n; ++i) { |
2318 |
+ |
if ((w = ws[i]) != null) { |
2319 |
+ |
w.runState = -1; |
2320 |
+ |
if (pass > 0) { |
2321 |
+ |
w.cancelAll(); |
2322 |
+ |
if (pass > 1) |
2323 |
+ |
w.interruptOwner(); |
2324 |
+ |
} |
2325 |
+ |
} |
2326 |
+ |
} |
2327 |
+ |
// Wake up workers parked on event queue |
2328 |
+ |
int i, e; long cc; Thread p; |
2329 |
+ |
while ((e = (int)(cc = ctl) & E_MASK) != 0 && |
2330 |
+ |
(i = e & SMASK) < n && |
2331 |
+ |
(w = ws[i]) != null) { |
2332 |
+ |
long nc = ((long)(w.nextWait & E_MASK) | |
2333 |
+ |
((cc + AC_UNIT) & AC_MASK) | |
2334 |
+ |
(cc & (TC_MASK|STOP_BIT))); |
2335 |
+ |
if (w.eventCount == (e | INT_SIGN) && |
2336 |
+ |
U.compareAndSwapLong(this, CTL, cc, nc)) { |
2337 |
+ |
w.eventCount = (e + E_SEQ) & E_MASK; |
2338 |
+ |
w.runState = -1; |
2339 |
+ |
if ((p = w.parker) != null) |
2340 |
+ |
U.unpark(p); |
2341 |
+ |
} |
2342 |
+ |
} |
2343 |
+ |
} |
2344 |
+ |
} |
2345 |
+ |
} |
2346 |
+ |
} |
2347 |
+ |
} |
2348 |
+ |
|
2349 |
|
// Exported methods |
2350 |
|
|
2351 |
|
// Constructors |
2415 |
|
checkPermission(); |
2416 |
|
if (factory == null) |
2417 |
|
throw new NullPointerException(); |
2418 |
< |
if (parallelism <= 0 || parallelism > MAX_ID) |
2418 |
> |
if (parallelism <= 0 || parallelism > MAX_CAP) |
2419 |
|
throw new IllegalArgumentException(); |
2420 |
|
this.parallelism = parallelism; |
2421 |
|
this.factory = factory; |
2422 |
|
this.ueh = handler; |
2423 |
< |
this.locallyFifo = asyncMode; |
2423 |
> |
this.localMode = asyncMode ? FIFO_QUEUE : LIFO_QUEUE; |
2424 |
|
long np = (long)(-parallelism); // offset ctl counts |
2425 |
|
this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK); |
2426 |
< |
this.submissionQueue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY]; |
2427 |
< |
// initialize workers array with room for 2*parallelism if possible |
2428 |
< |
int n = parallelism << 1; |
2429 |
< |
if (n >= MAX_ID) |
2430 |
< |
n = MAX_ID; |
1448 |
< |
else { // See Hackers Delight, sec 3.2, where n < (1 << 16) |
1449 |
< |
n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; |
1450 |
< |
} |
1451 |
< |
workers = new ForkJoinWorkerThread[n + 1]; |
1452 |
< |
this.submissionLock = new ReentrantLock(); |
1453 |
< |
this.termination = submissionLock.newCondition(); |
2426 |
> |
// Use nearest power 2 for workQueues size. See Hackers Delight sec 3.2. |
2427 |
> |
int n = parallelism - 1; |
2428 |
> |
n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; |
2429 |
> |
this.submitMask = ((n + 1) << 1) - 1; |
2430 |
> |
int pn = poolNumberGenerator.incrementAndGet(); |
2431 |
|
StringBuilder sb = new StringBuilder("ForkJoinPool-"); |
2432 |
< |
sb.append(poolNumberGenerator.incrementAndGet()); |
2432 |
> |
sb.append(Integer.toString(pn)); |
2433 |
|
sb.append("-worker-"); |
2434 |
|
this.workerNamePrefix = sb.toString(); |
2435 |
+ |
this.runState = 1; // set init flag |
2436 |
+ |
} |
2437 |
+ |
|
2438 |
+ |
/** |
2439 |
+ |
* Constructor for common pool, suitable only for static initialization. |
2440 |
+ |
* Basically the same as above, but uses smallest possible initial footprint. |
2441 |
+ |
*/ |
2442 |
+ |
ForkJoinPool(int parallelism, int submitMask, |
2443 |
+ |
ForkJoinWorkerThreadFactory factory, |
2444 |
+ |
Thread.UncaughtExceptionHandler handler) { |
2445 |
+ |
this.factory = factory; |
2446 |
+ |
this.ueh = handler; |
2447 |
+ |
this.submitMask = submitMask; |
2448 |
+ |
this.parallelism = parallelism; |
2449 |
+ |
long np = (long)(-parallelism); |
2450 |
+ |
this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK); |
2451 |
+ |
this.localMode = LIFO_QUEUE; |
2452 |
+ |
this.workerNamePrefix = "ForkJoinPool.commonPool-worker-"; |
2453 |
+ |
this.runState = 1; |
2454 |
+ |
} |
2455 |
+ |
|
2456 |
+ |
/** |
2457 |
+ |
* Returns the common pool instance. |
2458 |
+ |
* |
2459 |
+ |
* @return the common pool instance |
2460 |
+ |
*/ |
2461 |
+ |
public static ForkJoinPool commonPool() { |
2462 |
+ |
ForkJoinPool p; |
2463 |
+ |
if ((p = commonPool) == null) |
2464 |
+ |
throw new Error("Common Pool Unavailable"); |
2465 |
+ |
return p; |
2466 |
|
} |
2467 |
|
|
2468 |
|
// Execution methods |
2484 |
|
* scheduled for execution |
2485 |
|
*/ |
2486 |
|
public <T> T invoke(ForkJoinTask<T> task) { |
1479 |
– |
Thread t = Thread.currentThread(); |
2487 |
|
if (task == null) |
2488 |
|
throw new NullPointerException(); |
2489 |
< |
if (shutdown) |
2490 |
< |
throw new RejectedExecutionException(); |
1484 |
< |
if ((t instanceof ForkJoinWorkerThread) && |
1485 |
< |
((ForkJoinWorkerThread)t).pool == this) |
1486 |
< |
return task.invoke(); // bypass submit if in same pool |
1487 |
< |
else { |
1488 |
< |
addSubmission(task); |
1489 |
< |
return task.join(); |
1490 |
< |
} |
1491 |
< |
} |
1492 |
< |
|
1493 |
< |
/** |
1494 |
< |
* Unless terminating, forks task if within an ongoing FJ |
1495 |
< |
* computation in the current pool, else submits as external task. |
1496 |
< |
*/ |
1497 |
< |
private <T> void forkOrSubmit(ForkJoinTask<T> task) { |
1498 |
< |
ForkJoinWorkerThread w; |
1499 |
< |
Thread t = Thread.currentThread(); |
1500 |
< |
if (shutdown) |
1501 |
< |
throw new RejectedExecutionException(); |
1502 |
< |
if ((t instanceof ForkJoinWorkerThread) && |
1503 |
< |
(w = (ForkJoinWorkerThread)t).pool == this) |
1504 |
< |
w.pushTask(task); |
1505 |
< |
else |
1506 |
< |
addSubmission(task); |
2489 |
> |
doSubmit(task); |
2490 |
> |
return task.join(); |
2491 |
|
} |
2492 |
|
|
2493 |
|
/** |
2501 |
|
public void execute(ForkJoinTask<?> task) { |
2502 |
|
if (task == null) |
2503 |
|
throw new NullPointerException(); |
2504 |
< |
forkOrSubmit(task); |
2504 |
> |
doSubmit(task); |
2505 |
|
} |
2506 |
|
|
2507 |
|
// AbstractExecutorService methods |
2518 |
|
if (task instanceof ForkJoinTask<?>) // avoid re-wrap |
2519 |
|
job = (ForkJoinTask<?>) task; |
2520 |
|
else |
2521 |
< |
job = ForkJoinTask.adapt(task, null); |
2522 |
< |
forkOrSubmit(job); |
2521 |
> |
job = new ForkJoinTask.AdaptedRunnableAction(task); |
2522 |
> |
doSubmit(job); |
2523 |
|
} |
2524 |
|
|
2525 |
|
/** |
2534 |
|
public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) { |
2535 |
|
if (task == null) |
2536 |
|
throw new NullPointerException(); |
2537 |
< |
forkOrSubmit(task); |
2537 |
> |
doSubmit(task); |
2538 |
|
return task; |
2539 |
|
} |
2540 |
|
|
2544 |
|
* scheduled for execution |
2545 |
|
*/ |
2546 |
|
public <T> ForkJoinTask<T> submit(Callable<T> task) { |
2547 |
< |
if (task == null) |
2548 |
< |
throw new NullPointerException(); |
1565 |
< |
ForkJoinTask<T> job = ForkJoinTask.adapt(task); |
1566 |
< |
forkOrSubmit(job); |
2547 |
> |
ForkJoinTask<T> job = new ForkJoinTask.AdaptedCallable<T>(task); |
2548 |
> |
doSubmit(job); |
2549 |
|
return job; |
2550 |
|
} |
2551 |
|
|
2555 |
|
* scheduled for execution |
2556 |
|
*/ |
2557 |
|
public <T> ForkJoinTask<T> submit(Runnable task, T result) { |
2558 |
< |
if (task == null) |
2559 |
< |
throw new NullPointerException(); |
1578 |
< |
ForkJoinTask<T> job = ForkJoinTask.adapt(task, result); |
1579 |
< |
forkOrSubmit(job); |
2558 |
> |
ForkJoinTask<T> job = new ForkJoinTask.AdaptedRunnable<T>(task, result); |
2559 |
> |
doSubmit(job); |
2560 |
|
return job; |
2561 |
|
} |
2562 |
|
|
2572 |
|
if (task instanceof ForkJoinTask<?>) // avoid re-wrap |
2573 |
|
job = (ForkJoinTask<?>) task; |
2574 |
|
else |
2575 |
< |
job = ForkJoinTask.adapt(task, null); |
2576 |
< |
forkOrSubmit(job); |
2575 |
> |
job = new ForkJoinTask.AdaptedRunnableAction(task); |
2576 |
> |
doSubmit(job); |
2577 |
|
return job; |
2578 |
|
} |
2579 |
|
|
2582 |
|
* @throws RejectedExecutionException {@inheritDoc} |
2583 |
|
*/ |
2584 |
|
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) { |
2585 |
< |
ArrayList<ForkJoinTask<T>> forkJoinTasks = |
2586 |
< |
new ArrayList<ForkJoinTask<T>>(tasks.size()); |
2587 |
< |
for (Callable<T> task : tasks) |
2588 |
< |
forkJoinTasks.add(ForkJoinTask.adapt(task)); |
2589 |
< |
invoke(new InvokeAll<T>(forkJoinTasks)); |
2590 |
< |
|
2585 |
> |
// In previous versions of this class, this method constructed |
2586 |
> |
// a task to run ForkJoinTask.invokeAll, but now external |
2587 |
> |
// invocation of multiple tasks is at least as efficient. |
2588 |
> |
List<ForkJoinTask<T>> fs = new ArrayList<ForkJoinTask<T>>(tasks.size()); |
2589 |
> |
// Workaround needed because method wasn't declared with |
2590 |
> |
// wildcards in return type but should have been. |
2591 |
|
@SuppressWarnings({"unchecked", "rawtypes"}) |
2592 |
< |
List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks; |
1613 |
< |
return futures; |
1614 |
< |
} |
2592 |
> |
List<Future<T>> futures = (List<Future<T>>) (List) fs; |
2593 |
|
|
2594 |
< |
static final class InvokeAll<T> extends RecursiveAction { |
2595 |
< |
final ArrayList<ForkJoinTask<T>> tasks; |
2596 |
< |
InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; } |
2597 |
< |
public void compute() { |
2598 |
< |
try { invokeAll(tasks); } |
2599 |
< |
catch (Exception ignore) {} |
2594 |
> |
boolean done = false; |
2595 |
> |
try { |
2596 |
> |
for (Callable<T> t : tasks) { |
2597 |
> |
ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t); |
2598 |
> |
doSubmit(f); |
2599 |
> |
fs.add(f); |
2600 |
> |
} |
2601 |
> |
for (ForkJoinTask<T> f : fs) |
2602 |
> |
f.quietlyJoin(); |
2603 |
> |
done = true; |
2604 |
> |
return futures; |
2605 |
> |
} finally { |
2606 |
> |
if (!done) |
2607 |
> |
for (ForkJoinTask<T> f : fs) |
2608 |
> |
f.cancel(false); |
2609 |
|
} |
1623 |
– |
private static final long serialVersionUID = -7914297376763021607L; |
2610 |
|
} |
2611 |
|
|
2612 |
|
/** |
2638 |
|
} |
2639 |
|
|
2640 |
|
/** |
2641 |
+ |
* Returns the targeted parallelism level of the common pool. |
2642 |
+ |
* |
2643 |
+ |
* @return the targeted parallelism level of the common pool |
2644 |
+ |
*/ |
2645 |
+ |
public static int getCommonPoolParallelism() { |
2646 |
+ |
return commonPoolParallelism; |
2647 |
+ |
} |
2648 |
+ |
|
2649 |
+ |
/** |
2650 |
|
* Returns the number of worker threads that have started but not |
2651 |
|
* yet terminated. The result returned by this method may differ |
2652 |
|
* from {@link #getParallelism} when threads are created to |
2665 |
|
* @return {@code true} if this pool uses async mode |
2666 |
|
*/ |
2667 |
|
public boolean getAsyncMode() { |
2668 |
< |
return locallyFifo; |
2668 |
> |
return localMode != 0; |
2669 |
|
} |
2670 |
|
|
2671 |
|
/** |
2677 |
|
* @return the number of worker threads |
2678 |
|
*/ |
2679 |
|
public int getRunningThreadCount() { |
2680 |
< |
int r = parallelism + (int)(ctl >> AC_SHIFT); |
2681 |
< |
return (r <= 0) ? 0 : r; // suppress momentarily negative values |
2680 |
> |
int rc = 0; |
2681 |
> |
WorkQueue[] ws; WorkQueue w; |
2682 |
> |
if ((ws = workQueues) != null) { |
2683 |
> |
for (int i = 1; i < ws.length; i += 2) { |
2684 |
> |
if ((w = ws[i]) != null && w.isApparentlyUnblocked()) |
2685 |
> |
++rc; |
2686 |
> |
} |
2687 |
> |
} |
2688 |
> |
return rc; |
2689 |
|
} |
2690 |
|
|
2691 |
|
/** |
2696 |
|
* @return the number of active threads |
2697 |
|
*/ |
2698 |
|
public int getActiveThreadCount() { |
2699 |
< |
int r = parallelism + (int)(ctl >> AC_SHIFT) + blockedCount; |
2699 |
> |
int r = parallelism + (int)(ctl >> AC_SHIFT); |
2700 |
|
return (r <= 0) ? 0 : r; // suppress momentarily negative values |
2701 |
|
} |
2702 |
|
|
2712 |
|
* @return {@code true} if all threads are currently idle |
2713 |
|
*/ |
2714 |
|
public boolean isQuiescent() { |
2715 |
< |
return parallelism + (int)(ctl >> AC_SHIFT) + blockedCount == 0; |
2715 |
> |
return (int)(ctl >> AC_SHIFT) + parallelism == 0; |
2716 |
|
} |
2717 |
|
|
2718 |
|
/** |
2727 |
|
* @return the number of steals |
2728 |
|
*/ |
2729 |
|
public long getStealCount() { |
2730 |
< |
return stealCount; |
2730 |
> |
long count = stealCount; |
2731 |
> |
WorkQueue[] ws; WorkQueue w; |
2732 |
> |
if ((ws = workQueues) != null) { |
2733 |
> |
for (int i = 1; i < ws.length; i += 2) { |
2734 |
> |
if ((w = ws[i]) != null) |
2735 |
> |
count += w.totalSteals; |
2736 |
> |
} |
2737 |
> |
} |
2738 |
> |
return count; |
2739 |
|
} |
2740 |
|
|
2741 |
|
/** |
2750 |
|
*/ |
2751 |
|
public long getQueuedTaskCount() { |
2752 |
|
long count = 0; |
2753 |
< |
ForkJoinWorkerThread[] ws; |
2754 |
< |
if ((short)(ctl >>> TC_SHIFT) > -parallelism && |
2755 |
< |
(ws = workers) != null) { |
2756 |
< |
for (ForkJoinWorkerThread w : ws) |
2757 |
< |
if (w != null) |
2758 |
< |
count -= w.queueBase - w.queueTop; // must read base first |
2753 |
> |
WorkQueue[] ws; WorkQueue w; |
2754 |
> |
if ((ws = workQueues) != null) { |
2755 |
> |
for (int i = 1; i < ws.length; i += 2) { |
2756 |
> |
if ((w = ws[i]) != null) |
2757 |
> |
count += w.queueSize(); |
2758 |
> |
} |
2759 |
|
} |
2760 |
|
return count; |
2761 |
|
} |
2768 |
|
* @return the number of queued submissions |
2769 |
|
*/ |
2770 |
|
public int getQueuedSubmissionCount() { |
2771 |
< |
return -queueBase + queueTop; |
2771 |
> |
int count = 0; |
2772 |
> |
WorkQueue[] ws; WorkQueue w; |
2773 |
> |
if ((ws = workQueues) != null) { |
2774 |
> |
for (int i = 0; i < ws.length; i += 2) { |
2775 |
> |
if ((w = ws[i]) != null) |
2776 |
> |
count += w.queueSize(); |
2777 |
> |
} |
2778 |
> |
} |
2779 |
> |
return count; |
2780 |
|
} |
2781 |
|
|
2782 |
|
/** |
2786 |
|
* @return {@code true} if there are any queued submissions |
2787 |
|
*/ |
2788 |
|
public boolean hasQueuedSubmissions() { |
2789 |
< |
return queueBase != queueTop; |
2789 |
> |
WorkQueue[] ws; WorkQueue w; |
2790 |
> |
if ((ws = workQueues) != null) { |
2791 |
> |
for (int i = 0; i < ws.length; i += 2) { |
2792 |
> |
if ((w = ws[i]) != null && !w.isEmpty()) |
2793 |
> |
return true; |
2794 |
> |
} |
2795 |
> |
} |
2796 |
> |
return false; |
2797 |
|
} |
2798 |
|
|
2799 |
|
/** |
2804 |
|
* @return the next submission, or {@code null} if none |
2805 |
|
*/ |
2806 |
|
protected ForkJoinTask<?> pollSubmission() { |
2807 |
< |
ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i; |
2808 |
< |
while ((b = queueBase) != queueTop && |
2809 |
< |
(q = submissionQueue) != null && |
2810 |
< |
(i = (q.length - 1) & b) >= 0) { |
2811 |
< |
long u = (i << ASHIFT) + ABASE; |
1787 |
< |
if ((t = q[i]) != null && |
1788 |
< |
queueBase == b && |
1789 |
< |
UNSAFE.compareAndSwapObject(q, u, t, null)) { |
1790 |
< |
queueBase = b + 1; |
1791 |
< |
return t; |
2807 |
> |
WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t; |
2808 |
> |
if ((ws = workQueues) != null) { |
2809 |
> |
for (int i = 0; i < ws.length; i += 2) { |
2810 |
> |
if ((w = ws[i]) != null && (t = w.poll()) != null) |
2811 |
> |
return t; |
2812 |
|
} |
2813 |
|
} |
2814 |
|
return null; |
2833 |
|
*/ |
2834 |
|
protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) { |
2835 |
|
int count = 0; |
2836 |
< |
while (queueBase != queueTop) { |
2837 |
< |
ForkJoinTask<?> t = pollSubmission(); |
2838 |
< |
if (t != null) { |
2839 |
< |
c.add(t); |
2840 |
< |
++count; |
2836 |
> |
WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t; |
2837 |
> |
if ((ws = workQueues) != null) { |
2838 |
> |
for (int i = 0; i < ws.length; ++i) { |
2839 |
> |
if ((w = ws[i]) != null) { |
2840 |
> |
while ((t = w.poll()) != null) { |
2841 |
> |
c.add(t); |
2842 |
> |
++count; |
2843 |
> |
} |
2844 |
> |
} |
2845 |
|
} |
2846 |
|
} |
1823 |
– |
ForkJoinWorkerThread[] ws; |
1824 |
– |
if ((short)(ctl >>> TC_SHIFT) > -parallelism && |
1825 |
– |
(ws = workers) != null) { |
1826 |
– |
for (ForkJoinWorkerThread w : ws) |
1827 |
– |
if (w != null) |
1828 |
– |
count += w.drainTasksTo(c); |
1829 |
– |
} |
2847 |
|
return count; |
2848 |
|
} |
2849 |
|
|
2855 |
|
* @return a string identifying this pool, as well as its state |
2856 |
|
*/ |
2857 |
|
public String toString() { |
2858 |
< |
long st = getStealCount(); |
2859 |
< |
long qt = getQueuedTaskCount(); |
2860 |
< |
long qs = getQueuedSubmissionCount(); |
1844 |
< |
int pc = parallelism; |
2858 |
> |
// Use a single pass through workQueues to collect counts |
2859 |
> |
long qt = 0L, qs = 0L; int rc = 0; |
2860 |
> |
long st = stealCount; |
2861 |
|
long c = ctl; |
2862 |
+ |
WorkQueue[] ws; WorkQueue w; |
2863 |
+ |
if ((ws = workQueues) != null) { |
2864 |
+ |
for (int i = 0; i < ws.length; ++i) { |
2865 |
+ |
if ((w = ws[i]) != null) { |
2866 |
+ |
int size = w.queueSize(); |
2867 |
+ |
if ((i & 1) == 0) |
2868 |
+ |
qs += size; |
2869 |
+ |
else { |
2870 |
+ |
qt += size; |
2871 |
+ |
st += w.totalSteals; |
2872 |
+ |
if (w.isApparentlyUnblocked()) |
2873 |
+ |
++rc; |
2874 |
+ |
} |
2875 |
+ |
} |
2876 |
+ |
} |
2877 |
+ |
} |
2878 |
+ |
int pc = parallelism; |
2879 |
|
int tc = pc + (short)(c >>> TC_SHIFT); |
2880 |
< |
int rc = pc + (int)(c >> AC_SHIFT); |
2881 |
< |
if (rc < 0) // ignore transient negative |
2882 |
< |
rc = 0; |
1850 |
< |
int ac = rc + blockedCount; |
2880 |
> |
int ac = pc + (int)(c >> AC_SHIFT); |
2881 |
> |
if (ac < 0) // ignore transient negative |
2882 |
> |
ac = 0; |
2883 |
|
String level; |
2884 |
|
if ((c & STOP_BIT) != 0) |
2885 |
|
level = (tc == 0) ? "Terminated" : "Terminating"; |
2886 |
|
else |
2887 |
< |
level = shutdown ? "Shutting down" : "Running"; |
2887 |
> |
level = runState < 0 ? "Shutting down" : "Running"; |
2888 |
|
return super.toString() + |
2889 |
|
"[" + level + |
2890 |
|
", parallelism = " + pc + |
2898 |
|
} |
2899 |
|
|
2900 |
|
/** |
2901 |
< |
* Initiates an orderly shutdown in which previously submitted |
2902 |
< |
* tasks are executed, but no new tasks will be accepted. |
2903 |
< |
* Invocation has no additional effect if already shut down. |
2904 |
< |
* Tasks that are in the process of being submitted concurrently |
2905 |
< |
* during the course of this method may or may not be rejected. |
2901 |
> |
* Possibly initiates an orderly shutdown in which previously |
2902 |
> |
* submitted tasks are executed, but no new tasks will be |
2903 |
> |
* accepted. Invocation has no effect on execution state if this |
2904 |
> |
* is the {@link #commonPool}, and no additional effect if |
2905 |
> |
* already shut down. Tasks that are in the process of being |
2906 |
> |
* submitted concurrently during the course of this method may or |
2907 |
> |
* may not be rejected. |
2908 |
|
* |
2909 |
|
* @throws SecurityException if a security manager exists and |
2910 |
|
* the caller is not permitted to modify threads |
2913 |
|
*/ |
2914 |
|
public void shutdown() { |
2915 |
|
checkPermission(); |
2916 |
< |
shutdown = true; |
2917 |
< |
tryTerminate(false); |
2916 |
> |
if (this != commonPool) |
2917 |
> |
tryTerminate(false, true); |
2918 |
|
} |
2919 |
|
|
2920 |
|
/** |
2921 |
< |
* Attempts to cancel and/or stop all tasks, and reject all |
2922 |
< |
* subsequently submitted tasks. Tasks that are in the process of |
2923 |
< |
* being submitted or executed concurrently during the course of |
2924 |
< |
* this method may or may not be rejected. This method cancels |
2925 |
< |
* both existing and unexecuted tasks, in order to permit |
2926 |
< |
* termination in the presence of task dependencies. So the method |
2927 |
< |
* always returns an empty list (unlike the case for some other |
2928 |
< |
* Executors). |
2921 |
> |
* Possibly attempts to cancel and/or stop all tasks, and reject |
2922 |
> |
* all subsequently submitted tasks. Invocation has no effect on |
2923 |
> |
* execution state if this is the {@link #commonPool}, and no |
2924 |
> |
* additional effect if already shut down. Otherwise, tasks that |
2925 |
> |
* are in the process of being submitted or executed concurrently |
2926 |
> |
* during the course of this method may or may not be |
2927 |
> |
* rejected. This method cancels both existing and unexecuted |
2928 |
> |
* tasks, in order to permit termination in the presence of task |
2929 |
> |
* dependencies. So the method always returns an empty list |
2930 |
> |
* (unlike the case for some other Executors). |
2931 |
|
* |
2932 |
|
* @return an empty list |
2933 |
|
* @throws SecurityException if a security manager exists and |
2937 |
|
*/ |
2938 |
|
public List<Runnable> shutdownNow() { |
2939 |
|
checkPermission(); |
2940 |
< |
shutdown = true; |
2941 |
< |
tryTerminate(true); |
2940 |
> |
if (this != commonPool) |
2941 |
> |
tryTerminate(true, true); |
2942 |
|
return Collections.emptyList(); |
2943 |
|
} |
2944 |
|
|
2973 |
|
} |
2974 |
|
|
2975 |
|
/** |
1940 |
– |
* Returns true if terminating or terminated. Used by ForkJoinWorkerThread. |
1941 |
– |
*/ |
1942 |
– |
final boolean isAtLeastTerminating() { |
1943 |
– |
return (ctl & STOP_BIT) != 0L; |
1944 |
– |
} |
1945 |
– |
|
1946 |
– |
/** |
2976 |
|
* Returns {@code true} if this pool has been shut down. |
2977 |
|
* |
2978 |
|
* @return {@code true} if this pool has been shut down |
2979 |
|
*/ |
2980 |
|
public boolean isShutdown() { |
2981 |
< |
return shutdown; |
2981 |
> |
return runState < 0; |
2982 |
|
} |
2983 |
|
|
2984 |
|
/** |
2995 |
|
public boolean awaitTermination(long timeout, TimeUnit unit) |
2996 |
|
throws InterruptedException { |
2997 |
|
long nanos = unit.toNanos(timeout); |
2998 |
< |
final ReentrantLock lock = this.submissionLock; |
2999 |
< |
lock.lock(); |
3000 |
< |
try { |
3001 |
< |
for (;;) { |
3002 |
< |
if (isTerminated()) |
3003 |
< |
return true; |
3004 |
< |
if (nanos <= 0) |
3005 |
< |
return false; |
3006 |
< |
nanos = termination.awaitNanos(nanos); |
2998 |
> |
if (isTerminated()) |
2999 |
> |
return true; |
3000 |
> |
long startTime = System.nanoTime(); |
3001 |
> |
boolean terminated = false; |
3002 |
> |
synchronized (this) { |
3003 |
> |
for (long waitTime = nanos, millis = 0L;;) { |
3004 |
> |
if (terminated = isTerminated() || |
3005 |
> |
waitTime <= 0L || |
3006 |
> |
(millis = unit.toMillis(waitTime)) <= 0L) |
3007 |
> |
break; |
3008 |
> |
wait(millis); |
3009 |
> |
waitTime = nanos - (System.nanoTime() - startTime); |
3010 |
|
} |
1979 |
– |
} finally { |
1980 |
– |
lock.unlock(); |
3011 |
|
} |
3012 |
+ |
return terminated; |
3013 |
|
} |
3014 |
|
|
3015 |
|
/** |
3108 |
|
public static void managedBlock(ManagedBlocker blocker) |
3109 |
|
throws InterruptedException { |
3110 |
|
Thread t = Thread.currentThread(); |
3111 |
< |
if (t instanceof ForkJoinWorkerThread) { |
3112 |
< |
ForkJoinWorkerThread w = (ForkJoinWorkerThread) t; |
3113 |
< |
w.pool.awaitBlocker(blocker); |
3114 |
< |
} |
3115 |
< |
else { |
3116 |
< |
do {} while (!blocker.isReleasable() && !blocker.block()); |
3111 |
> |
ForkJoinPool p = ((t instanceof ForkJoinWorkerThread) ? |
3112 |
> |
((ForkJoinWorkerThread)t).pool : null); |
3113 |
> |
while (!blocker.isReleasable()) { |
3114 |
> |
if (p == null || p.tryCompensate(null, blocker)) { |
3115 |
> |
try { |
3116 |
> |
do {} while (!blocker.isReleasable() && !blocker.block()); |
3117 |
> |
} finally { |
3118 |
> |
if (p != null) |
3119 |
> |
p.incrementActiveCount(); |
3120 |
> |
} |
3121 |
> |
break; |
3122 |
> |
} |
3123 |
|
} |
3124 |
|
} |
3125 |
|
|
3128 |
|
// implement RunnableFuture. |
3129 |
|
|
3130 |
|
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) { |
3131 |
< |
return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value); |
3131 |
> |
return new ForkJoinTask.AdaptedRunnable<T>(runnable, value); |
3132 |
|
} |
3133 |
|
|
3134 |
|
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) { |
3135 |
< |
return (RunnableFuture<T>) ForkJoinTask.adapt(callable); |
3135 |
> |
return new ForkJoinTask.AdaptedCallable<T>(callable); |
3136 |
|
} |
3137 |
|
|
3138 |
|
// Unsafe mechanics |
3139 |
< |
private static final sun.misc.Unsafe UNSAFE; |
3140 |
< |
private static final long ctlOffset; |
3141 |
< |
private static final long stealCountOffset; |
3142 |
< |
private static final long blockedCountOffset; |
2106 |
< |
private static final long quiescerCountOffset; |
2107 |
< |
private static final long scanGuardOffset; |
2108 |
< |
private static final long nextWorkerNumberOffset; |
2109 |
< |
private static final long ABASE; |
3139 |
> |
private static final sun.misc.Unsafe U; |
3140 |
> |
private static final long CTL; |
3141 |
> |
private static final long PARKBLOCKER; |
3142 |
> |
private static final int ABASE; |
3143 |
|
private static final int ASHIFT; |
3144 |
+ |
private static final long NEXTWORKERNUMBER; |
3145 |
+ |
private static final long STEALCOUNT; |
3146 |
+ |
private static final long MAINLOCK; |
3147 |
|
|
3148 |
|
static { |
3149 |
|
poolNumberGenerator = new AtomicInteger(); |
3150 |
< |
workerSeedGenerator = new Random(); |
3150 |
> |
nextSubmitterSeed = new AtomicInteger(0x55555555); |
3151 |
|
modifyThreadPermission = new RuntimePermission("modifyThread"); |
3152 |
|
defaultForkJoinWorkerThreadFactory = |
3153 |
|
new DefaultForkJoinWorkerThreadFactory(); |
3154 |
+ |
submitters = new ThreadSubmitter(); |
3155 |
+ |
int s; |
3156 |
|
try { |
3157 |
< |
UNSAFE = getUnsafe(); |
3157 |
> |
U = getUnsafe(); |
3158 |
|
Class<?> k = ForkJoinPool.class; |
3159 |
< |
ctlOffset = UNSAFE.objectFieldOffset |
3159 |
> |
Class<?> ak = ForkJoinTask[].class; |
3160 |
> |
CTL = U.objectFieldOffset |
3161 |
|
(k.getDeclaredField("ctl")); |
3162 |
< |
stealCountOffset = UNSAFE.objectFieldOffset |
2124 |
< |
(k.getDeclaredField("stealCount")); |
2125 |
< |
blockedCountOffset = UNSAFE.objectFieldOffset |
2126 |
< |
(k.getDeclaredField("blockedCount")); |
2127 |
< |
quiescerCountOffset = UNSAFE.objectFieldOffset |
2128 |
< |
(k.getDeclaredField("quiescerCount")); |
2129 |
< |
scanGuardOffset = UNSAFE.objectFieldOffset |
2130 |
< |
(k.getDeclaredField("scanGuard")); |
2131 |
< |
nextWorkerNumberOffset = UNSAFE.objectFieldOffset |
3162 |
> |
NEXTWORKERNUMBER = U.objectFieldOffset |
3163 |
|
(k.getDeclaredField("nextWorkerNumber")); |
3164 |
+ |
STEALCOUNT = U.objectFieldOffset |
3165 |
+ |
(k.getDeclaredField("stealCount")); |
3166 |
+ |
MAINLOCK = U.objectFieldOffset |
3167 |
+ |
(k.getDeclaredField("mainLock")); |
3168 |
+ |
Class<?> tk = Thread.class; |
3169 |
+ |
PARKBLOCKER = U.objectFieldOffset |
3170 |
+ |
(tk.getDeclaredField("parkBlocker")); |
3171 |
+ |
ABASE = U.arrayBaseOffset(ak); |
3172 |
+ |
s = U.arrayIndexScale(ak); |
3173 |
+ |
ASHIFT = 31 - Integer.numberOfLeadingZeros(s); |
3174 |
|
} catch (Exception e) { |
3175 |
|
throw new Error(e); |
3176 |
|
} |
2136 |
– |
Class<?> a = ForkJoinTask[].class; |
2137 |
– |
ABASE = UNSAFE.arrayBaseOffset(a); |
2138 |
– |
int s = UNSAFE.arrayIndexScale(a); |
3177 |
|
if ((s & (s-1)) != 0) |
3178 |
|
throw new Error("data type scale not a power of two"); |
3179 |
< |
ASHIFT = 31 - Integer.numberOfLeadingZeros(s); |
3179 |
> |
try { // Establish common pool |
3180 |
> |
String pp = System.getProperty(propPrefix + "parallelism"); |
3181 |
> |
String fp = System.getProperty(propPrefix + "threadFactory"); |
3182 |
> |
String up = System.getProperty(propPrefix + "exceptionHandler"); |
3183 |
> |
ForkJoinWorkerThreadFactory fac = (fp == null) ? |
3184 |
> |
defaultForkJoinWorkerThreadFactory : |
3185 |
> |
((ForkJoinWorkerThreadFactory)ClassLoader. |
3186 |
> |
getSystemClassLoader().loadClass(fp).newInstance()); |
3187 |
> |
Thread.UncaughtExceptionHandler ueh = (up == null) ? null : |
3188 |
> |
((Thread.UncaughtExceptionHandler)ClassLoader. |
3189 |
> |
getSystemClassLoader().loadClass(up).newInstance()); |
3190 |
> |
int par; |
3191 |
> |
if ((pp == null || (par = Integer.parseInt(pp)) <= 0)) |
3192 |
> |
par = Runtime.getRuntime().availableProcessors(); |
3193 |
> |
if (par > MAX_CAP) |
3194 |
> |
par = MAX_CAP; |
3195 |
> |
commonPoolParallelism = par; |
3196 |
> |
int n = par - 1; // precompute submit mask |
3197 |
> |
n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; |
3198 |
> |
n |= n >>> 8; n |= n >>> 16; |
3199 |
> |
int mask = ((n + 1) << 1) - 1; |
3200 |
> |
commonPool = new ForkJoinPool(par, mask, fac, ueh); |
3201 |
> |
} catch (Exception e) { |
3202 |
> |
throw new Error(e); |
3203 |
> |
} |
3204 |
|
} |
3205 |
|
|
3206 |
|
/** |
3230 |
|
} |
3231 |
|
} |
3232 |
|
} |
3233 |
+ |
|
3234 |
|
} |