1 |
|
/* |
2 |
|
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
|
* Expert Group and released to the public domain, as explained at |
4 |
< |
* http://creativecommons.org/licenses/publicdomain |
4 |
> |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
|
*/ |
6 |
|
|
7 |
|
package jsr166y; |
8 |
< |
import java.util.*; |
9 |
< |
import java.util.concurrent.*; |
10 |
< |
import java.util.concurrent.locks.*; |
11 |
< |
import java.util.concurrent.atomic.*; |
12 |
< |
import sun.misc.Unsafe; |
13 |
< |
import java.lang.reflect.*; |
8 |
> |
|
9 |
> |
import java.util.ArrayList; |
10 |
> |
import java.util.Arrays; |
11 |
> |
import java.util.Collection; |
12 |
> |
import java.util.Collections; |
13 |
> |
import java.util.List; |
14 |
> |
import java.util.Random; |
15 |
> |
import java.util.concurrent.AbstractExecutorService; |
16 |
> |
import java.util.concurrent.Callable; |
17 |
> |
import java.util.concurrent.ExecutorService; |
18 |
> |
import java.util.concurrent.Future; |
19 |
> |
import java.util.concurrent.RejectedExecutionException; |
20 |
> |
import java.util.concurrent.RunnableFuture; |
21 |
> |
import java.util.concurrent.TimeUnit; |
22 |
> |
import java.util.concurrent.atomic.AtomicInteger; |
23 |
> |
import java.util.concurrent.atomic.AtomicLong; |
24 |
> |
import java.util.concurrent.locks.ReentrantLock; |
25 |
> |
import java.util.concurrent.locks.Condition; |
26 |
|
|
27 |
|
/** |
28 |
< |
* An {@link ExecutorService} for running {@link ForkJoinTask}s. A |
29 |
< |
* ForkJoinPool provides the entry point for submissions from |
30 |
< |
* non-ForkJoinTasks, as well as management and monitoring operations. |
31 |
< |
* Normally a single ForkJoinPool is used for a large number of |
20 |
< |
* submitted tasks. Otherwise, use would not usually outweigh the |
21 |
< |
* construction and bookkeeping overhead of creating a large set of |
22 |
< |
* threads. |
28 |
> |
* An {@link ExecutorService} for running {@link ForkJoinTask}s. |
29 |
> |
* A {@code ForkJoinPool} provides the entry point for submissions |
30 |
> |
* from non-{@code ForkJoinTask} clients, as well as management and |
31 |
> |
* monitoring operations. |
32 |
|
* |
33 |
< |
* <p>ForkJoinPools differ from other kinds of Executors mainly in |
34 |
< |
* that they provide <em>work-stealing</em>: all threads in the pool |
35 |
< |
* attempt to find and execute subtasks created by other active tasks |
36 |
< |
* (eventually blocking if none exist). This makes them efficient when |
37 |
< |
* most tasks spawn other subtasks (as do most ForkJoinTasks), as well |
38 |
< |
* as the mixed execution of some plain Runnable- or Callable- based |
39 |
< |
* activities along with ForkJoinTasks. When setting |
40 |
< |
* <tt>setAsyncMode</tt>, a ForkJoinPools may also be appropriate for |
41 |
< |
* use with fine-grained tasks that are never joined. Otherwise, other |
42 |
< |
* ExecutorService implementations are typically more appropriate |
43 |
< |
* choices. |
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 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 ForkJoinPool may be constructed with a given parallelism level |
46 |
< |
* (target pool size), which it attempts to maintain by dynamically |
47 |
< |
* adding, suspending, or resuming threads, even if some tasks are |
48 |
< |
* waiting to join others. However, no such adjustments are performed |
49 |
< |
* in the face of blocked IO or other unmanaged synchronization. The |
50 |
< |
* nested <code>ManagedBlocker</code> interface enables extension of |
51 |
< |
* the kinds of synchronization accommodated. The target parallelism |
52 |
< |
* level may also be changed dynamically (<code>setParallelism</code>) |
53 |
< |
* and thread construction can be limited using methods |
45 |
< |
* <code>setMaximumPoolSize</code> and/or |
46 |
< |
* <code>setMaintainsParallelism</code>. |
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 |
53 |
> |
* synchronization accommodated. |
54 |
|
* |
55 |
|
* <p>In addition to execution and lifecycle control methods, this |
56 |
|
* class provides status check methods (for example |
57 |
< |
* <code>getStealCount</code>) that are intended to aid in developing, |
57 |
> |
* {@link #getStealCount}) that are intended to aid in developing, |
58 |
|
* tuning, and monitoring fork/join applications. Also, method |
59 |
< |
* <code>toString</code> returns indications of pool state in a |
59 |
> |
* {@link #toString} returns indications of pool state in a |
60 |
|
* convenient form for informal monitoring. |
61 |
|
* |
62 |
+ |
* <p> As is the case with other ExecutorServices, there are three |
63 |
+ |
* main task execution methods summarized in the following table. |
64 |
+ |
* These are designed to be used primarily by clients not already |
65 |
+ |
* engaged in fork/join computations in the current pool. The main |
66 |
+ |
* forms of these methods accept instances of {@code ForkJoinTask}, |
67 |
+ |
* but overloaded forms also allow mixed execution of plain {@code |
68 |
+ |
* Runnable}- or {@code Callable}- based activities as well. However, |
69 |
+ |
* tasks that are already executing in a pool should normally instead |
70 |
+ |
* use the within-computation forms listed in the table unless using |
71 |
+ |
* async event-style tasks that are not usually joined, in which case |
72 |
+ |
* there is little difference among choice of methods. |
73 |
+ |
* |
74 |
+ |
* <table BORDER CELLPADDING=3 CELLSPACING=1> |
75 |
+ |
* <tr> |
76 |
+ |
* <td></td> |
77 |
+ |
* <td ALIGN=CENTER> <b>Call from non-fork/join clients</b></td> |
78 |
+ |
* <td ALIGN=CENTER> <b>Call from within fork/join computations</b></td> |
79 |
+ |
* </tr> |
80 |
+ |
* <tr> |
81 |
+ |
* <td> <b>Arrange async execution</td> |
82 |
+ |
* <td> {@link #execute(ForkJoinTask)}</td> |
83 |
+ |
* <td> {@link ForkJoinTask#fork}</td> |
84 |
+ |
* </tr> |
85 |
+ |
* <tr> |
86 |
+ |
* <td> <b>Await and obtain result</td> |
87 |
+ |
* <td> {@link #invoke(ForkJoinTask)}</td> |
88 |
+ |
* <td> {@link ForkJoinTask#invoke}</td> |
89 |
+ |
* </tr> |
90 |
+ |
* <tr> |
91 |
+ |
* <td> <b>Arrange exec and obtain Future</td> |
92 |
+ |
* <td> {@link #submit(ForkJoinTask)}</td> |
93 |
+ |
* <td> {@link ForkJoinTask#fork} (ForkJoinTasks <em>are</em> Futures)</td> |
94 |
+ |
* </tr> |
95 |
+ |
* </table> |
96 |
+ |
* |
97 |
+ |
* <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is |
98 |
+ |
* used for all parallel task execution in a program or subsystem. |
99 |
+ |
* Otherwise, use would not usually outweigh the construction and |
100 |
+ |
* bookkeeping overhead of creating a large set of threads. For |
101 |
+ |
* example, a common pool could be used for the {@code SortTasks} |
102 |
+ |
* illustrated in {@link RecursiveAction}. Because {@code |
103 |
+ |
* ForkJoinPool} uses threads in {@linkplain java.lang.Thread#isDaemon |
104 |
+ |
* daemon} mode, there is typically no need to explicitly {@link |
105 |
+ |
* #shutdown} such a pool upon program exit. |
106 |
+ |
* |
107 |
+ |
* <pre> {@code |
108 |
+ |
* static final ForkJoinPool mainPool = new ForkJoinPool(); |
109 |
+ |
* ... |
110 |
+ |
* public void sort(long[] array) { |
111 |
+ |
* mainPool.invoke(new SortTask(array, 0, array.length)); |
112 |
+ |
* }}</pre> |
113 |
+ |
* |
114 |
|
* <p><b>Implementation notes</b>: This implementation restricts the |
115 |
|
* maximum number of running threads to 32767. Attempts to create |
116 |
< |
* pools with greater than the maximum result in |
117 |
< |
* IllegalArgumentExceptions. |
116 |
> |
* pools with greater than the maximum number result in |
117 |
> |
* {@code IllegalArgumentException}. |
118 |
> |
* |
119 |
> |
* <p>This implementation rejects submitted tasks (that is, by throwing |
120 |
> |
* {@link RejectedExecutionException}) only when the pool is shut down |
121 |
> |
* or internal resources have been exhausted. |
122 |
> |
* |
123 |
> |
* @since 1.7 |
124 |
> |
* @author Doug Lea |
125 |
|
*/ |
126 |
|
public class ForkJoinPool extends AbstractExecutorService { |
127 |
|
|
128 |
|
/* |
129 |
< |
* See the extended comments interspersed below for design, |
130 |
< |
* rationale, and walkthroughs. |
131 |
< |
*/ |
132 |
< |
|
133 |
< |
/** Mask for packing and unpacking shorts */ |
134 |
< |
private static final int shortMask = 0xffff; |
135 |
< |
|
136 |
< |
/** Max pool size -- must be a power of two minus 1 */ |
137 |
< |
private static final int MAX_THREADS = 0x7FFF; |
138 |
< |
|
139 |
< |
/** |
140 |
< |
* Factory for creating new ForkJoinWorkerThreads. A |
141 |
< |
* ForkJoinWorkerThreadFactory must be defined and used for |
142 |
< |
* ForkJoinWorkerThread subclasses that extend base functionality |
143 |
< |
* or initialize threads with different contexts. |
129 |
> |
* Implementation Overview |
130 |
> |
* |
131 |
> |
* This class and its nested classes provide the main |
132 |
> |
* functionality and control for a set of worker threads: |
133 |
> |
* Submissions from non-FJ threads enter into submission queues. |
134 |
> |
* Workers take these tasks and typically split them into subtasks |
135 |
> |
* that may be stolen by other workers. Preference rules give |
136 |
> |
* first priority to processing tasks from their own queues (LIFO |
137 |
> |
* or FIFO, depending on mode), then to randomized FIFO steals of |
138 |
> |
* tasks in other queues. |
139 |
> |
* |
140 |
> |
* WorkQueues |
141 |
> |
* ========== |
142 |
> |
* |
143 |
> |
* Most operations occur within work-stealing queues (in nested |
144 |
> |
* class WorkQueue). These are special forms of Deques that |
145 |
> |
* support only three of the four possible end-operations -- push, |
146 |
> |
* pop, and poll (aka steal), under the further constraints that |
147 |
> |
* push and pop are called only from the owning thread (or, as |
148 |
> |
* extended here, under a lock), while poll may be called from |
149 |
> |
* other threads. (If you are unfamiliar with them, you probably |
150 |
> |
* want to read Herlihy and Shavit's book "The Art of |
151 |
> |
* Multiprocessor programming", chapter 16 describing these in |
152 |
> |
* more detail before proceeding.) The main work-stealing queue |
153 |
> |
* design is roughly similar to those in the papers "Dynamic |
154 |
> |
* Circular Work-Stealing Deque" by Chase and Lev, SPAA 2005 |
155 |
> |
* (http://research.sun.com/scalable/pubs/index.html) and |
156 |
> |
* "Idempotent work stealing" by Michael, Saraswat, and Vechev, |
157 |
> |
* PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186). |
158 |
> |
* The main differences ultimately stem from GC requirements that |
159 |
> |
* we null out taken slots as soon as we can, to maintain as small |
160 |
> |
* a footprint as possible even in programs generating huge |
161 |
> |
* numbers of tasks. To accomplish this, we shift the CAS |
162 |
> |
* arbitrating pop vs poll (steal) from being on the indices |
163 |
> |
* ("base" and "top") to the slots themselves. So, both a |
164 |
> |
* successful pop and poll mainly entail a CAS of a slot from |
165 |
> |
* non-null to null. Because we rely on CASes of references, we |
166 |
> |
* do not need tag bits on base or top. They are simple ints as |
167 |
> |
* used in any circular array-based queue (see for example |
168 |
> |
* ArrayDeque). Updates to the indices must still be ordered in a |
169 |
> |
* way that guarantees that top == base means the queue is empty, |
170 |
> |
* but otherwise may err on the side of possibly making the queue |
171 |
> |
* appear nonempty when a push, pop, or poll have not fully |
172 |
> |
* committed. Note that this means that the poll operation, |
173 |
> |
* considered individually, is not wait-free. One thief cannot |
174 |
> |
* successfully continue until another in-progress one (or, if |
175 |
> |
* previously empty, a push) completes. However, in the |
176 |
> |
* aggregate, we ensure at least probabilistic non-blockingness. |
177 |
> |
* If an attempted steal fails, a thief always chooses a different |
178 |
> |
* random victim target to try next. So, in order for one thief to |
179 |
> |
* progress, it suffices for any in-progress poll or new push on |
180 |
> |
* any empty queue to complete. |
181 |
> |
* |
182 |
> |
* This approach also enables support of a user mode in which local |
183 |
> |
* task processing is in FIFO, not LIFO order, simply by using |
184 |
> |
* poll rather than pop. This can be useful in message-passing |
185 |
> |
* frameworks in which tasks are never joined. However neither |
186 |
> |
* mode considers affinities, loads, cache localities, etc, so |
187 |
> |
* rarely provide the best possible performance on a given |
188 |
> |
* machine, but portably provide good throughput by averaging over |
189 |
> |
* these factors. (Further, even if we did try to use such |
190 |
> |
* information, we do not usually have a basis for exploiting it. |
191 |
> |
* For example, some sets of tasks profit from cache affinities, |
192 |
> |
* but others are harmed by cache pollution effects.) |
193 |
> |
* |
194 |
> |
* WorkQueues are also used in a similar way for tasks submitted |
195 |
> |
* to the pool. We cannot mix these tasks in the same queues used |
196 |
> |
* for work-stealing (this would contaminate lifo/fifo |
197 |
> |
* processing). Instead, we loosely associate submission queues |
198 |
> |
* with submitting threads, using a form of hashing. The |
199 |
> |
* ThreadLocal Submitter class contains a value initially used as |
200 |
> |
* a hash code for choosing existing queues, but may be randomly |
201 |
> |
* repositioned upon contention with other submitters. In |
202 |
> |
* essence, submitters act like workers except that they never |
203 |
> |
* take tasks, and they are multiplexed on to a finite number of |
204 |
> |
* shared work queues. However, classes are set up so that future |
205 |
> |
* extensions could allow submitters to optionally help perform |
206 |
> |
* tasks as well. Pool submissions from internal workers are also |
207 |
> |
* allowed, but use randomized rather than thread-hashed queue |
208 |
> |
* indices to avoid imbalance. Insertion of tasks in shared mode |
209 |
> |
* requires a lock (mainly to protect in the case of resizing) but |
210 |
> |
* we use only a simple spinlock (using bits in field runState), |
211 |
> |
* because submitters encountering a busy queue try or create |
212 |
> |
* others so never block. |
213 |
> |
* |
214 |
> |
* Management |
215 |
> |
* ========== |
216 |
> |
* |
217 |
> |
* The main throughput advantages of work-stealing stem from |
218 |
> |
* decentralized control -- workers mostly take tasks from |
219 |
> |
* themselves or each other. We cannot negate this in the |
220 |
> |
* implementation of other management responsibilities. The main |
221 |
> |
* tactic for avoiding bottlenecks is packing nearly all |
222 |
> |
* essentially atomic control state into two volatile variables |
223 |
> |
* that are by far most often read (not written) as status and |
224 |
> |
* consistency checks. |
225 |
> |
* |
226 |
> |
* Field "ctl" contains 64 bits holding all the information needed |
227 |
> |
* to atomically decide to add, inactivate, enqueue (on an event |
228 |
> |
* queue), dequeue, and/or re-activate workers. To enable this |
229 |
> |
* packing, we restrict maximum parallelism to (1<<15)-1 (which is |
230 |
> |
* far in excess of normal operating range) to allow ids, counts, |
231 |
> |
* and their negations (used for thresholding) to fit into 16bit |
232 |
> |
* fields. |
233 |
> |
* |
234 |
> |
* Field "runState" contains 32 bits needed to register and |
235 |
> |
* deregister WorkQueues, as well as to enable shutdown. It is |
236 |
> |
* only modified under a lock (normally briefly held, but |
237 |
> |
* occasionally protecting allocations and resizings) but even |
238 |
> |
* when locked remains available to check consistency. |
239 |
> |
* |
240 |
> |
* Recording WorkQueues. WorkQueues are recorded in the |
241 |
> |
* "workQueues" array that is created upon pool construction and |
242 |
> |
* expanded if necessary. Updates to the array while recording |
243 |
> |
* new workers and unrecording terminated ones are protected from |
244 |
> |
* each other by a lock but the array is otherwise concurrently |
245 |
> |
* readable, and accessed directly. To simplify index-based |
246 |
> |
* operations, the array size is always a power of two, and all |
247 |
> |
* readers must tolerate null slots. Shared (submission) queues |
248 |
> |
* are at even indices, worker queues at odd indices. Grouping |
249 |
> |
* them together in this way simplifies and speeds up task |
250 |
> |
* scanning. To avoid flailing during start-up, the array is |
251 |
> |
* presized to hold twice #parallelism workers (which is unlikely |
252 |
> |
* to need further resizing during execution). But to avoid |
253 |
> |
* dealing with so many null slots, variable runState includes a |
254 |
> |
* mask for the nearest power of two that contains all current |
255 |
> |
* workers. All worker thread creation is on-demand, triggered by |
256 |
> |
* task submissions, replacement of terminated workers, and/or |
257 |
> |
* compensation for blocked workers. However, all other support |
258 |
> |
* code is set up to work with other policies. To ensure that we |
259 |
> |
* do not hold on to worker references that would prevent GC, ALL |
260 |
> |
* accesses to workQueues are via indices into the workQueues |
261 |
> |
* array (which is one source of some of the messy code |
262 |
> |
* constructions here). In essence, the workQueues array serves as |
263 |
> |
* a weak reference mechanism. Thus for example the wait queue |
264 |
> |
* field of ctl stores indices, not references. Access to the |
265 |
> |
* workQueues in associated methods (for example signalWork) must |
266 |
> |
* both index-check and null-check the IDs. All such accesses |
267 |
> |
* ignore bad IDs by returning out early from what they are doing, |
268 |
> |
* since this can only be associated with termination, in which |
269 |
> |
* case it is OK to give up. |
270 |
> |
* |
271 |
> |
* All uses of the workQueues array check that it is non-null |
272 |
> |
* (even if previously non-null). This allows nulling during |
273 |
> |
* termination, which is currently not necessary, but remains an |
274 |
> |
* option for resource-revocation-based shutdown schemes. It also |
275 |
> |
* helps reduce JIT issuance of uncommon-trap code, which tends to |
276 |
> |
* unnecessarily complicate control flow in some methods. |
277 |
> |
* |
278 |
> |
* Event Queuing. Unlike HPC work-stealing frameworks, we cannot |
279 |
> |
* let workers spin indefinitely scanning for tasks when none can |
280 |
> |
* be found immediately, and we cannot start/resume workers unless |
281 |
> |
* there appear to be tasks available. On the other hand, we must |
282 |
> |
* quickly prod them into action when new tasks are submitted or |
283 |
> |
* generated. In many usages, ramp-up time to activate workers is |
284 |
> |
* the main limiting factor in overall performance (this is |
285 |
> |
* compounded at program start-up by JIT compilation and |
286 |
> |
* allocation). So we try to streamline this as much as possible. |
287 |
> |
* We park/unpark workers after placing in an event wait queue |
288 |
> |
* when they cannot find work. This "queue" is actually a simple |
289 |
> |
* Treiber stack, headed by the "id" field of ctl, plus a 15bit |
290 |
> |
* counter value (that reflects the number of times a worker has |
291 |
> |
* been inactivated) to avoid ABA effects (we need only as many |
292 |
> |
* version numbers as worker threads). Successors are held in |
293 |
> |
* field WorkQueue.nextWait. Queuing deals with several intrinsic |
294 |
> |
* races, mainly that a task-producing thread can miss seeing (and |
295 |
> |
* signalling) another thread that gave up looking for work but |
296 |
> |
* has not yet entered the wait queue. We solve this by requiring |
297 |
> |
* a full sweep of all workers (via repeated calls to method |
298 |
> |
* scan()) both before and after a newly waiting worker is added |
299 |
> |
* to the wait queue. During a rescan, the worker might release |
300 |
> |
* some other queued worker rather than itself, which has the same |
301 |
> |
* net effect. Because enqueued workers may actually be rescanning |
302 |
> |
* rather than waiting, we set and clear the "parker" field of |
303 |
> |
* WorkQueues to reduce unnecessary calls to unpark. (This |
304 |
> |
* requires a secondary recheck to avoid missed signals.) Note |
305 |
> |
* the unusual conventions about Thread.interrupts surrounding |
306 |
> |
* parking and other blocking: Because interrupts are used solely |
307 |
> |
* to alert threads to check termination, which is checked anyway |
308 |
> |
* upon blocking, we clear status (using Thread.interrupted) |
309 |
> |
* before any call to park, so that park does not immediately |
310 |
> |
* return due to status being set via some other unrelated call to |
311 |
> |
* interrupt in user code. |
312 |
> |
* |
313 |
> |
* Signalling. We create or wake up workers only when there |
314 |
> |
* appears to be at least one task they might be able to find and |
315 |
> |
* execute. When a submission is added or another worker adds a |
316 |
> |
* task to a queue that previously had fewer than two tasks, they |
317 |
> |
* signal waiting workers (or trigger creation of new ones if |
318 |
> |
* fewer than the given parallelism level -- see signalWork). |
319 |
> |
* These primary signals are buttressed by signals during rescans; |
320 |
> |
* together these cover the signals needed in cases when more |
321 |
> |
* tasks are pushed but untaken, and improve performance compared |
322 |
> |
* to having one thread wake up all workers. |
323 |
> |
* |
324 |
> |
* Trimming workers. To release resources after periods of lack of |
325 |
> |
* use, a worker starting to wait when the pool is quiescent will |
326 |
> |
* time out and terminate if the pool has remained quiescent for |
327 |
> |
* SHRINK_RATE nanosecs. This will slowly propagate, eventually |
328 |
> |
* terminating all workers after long periods of non-use. |
329 |
> |
* |
330 |
> |
* Shutdown and Termination. A call to shutdownNow atomically sets |
331 |
> |
* a runState bit and then (non-atomically) sets each worker's |
332 |
> |
* runState status, cancels all unprocessed tasks, and wakes up |
333 |
> |
* all waiting workers. Detecting whether termination should |
334 |
> |
* commence after a non-abrupt shutdown() call requires more work |
335 |
> |
* and bookkeeping. We need consensus about quiescence (i.e., that |
336 |
> |
* there is no more work). The active count provides a primary |
337 |
> |
* indication but non-abrupt shutdown still requires a rechecking |
338 |
> |
* scan for any workers that are inactive but not queued. |
339 |
> |
* |
340 |
> |
* Joining Tasks |
341 |
> |
* ============= |
342 |
> |
* |
343 |
> |
* Any of several actions may be taken when one worker is waiting |
344 |
> |
* to join a task stolen (or always held) by another. Because we |
345 |
> |
* are multiplexing many tasks on to a pool of workers, we can't |
346 |
> |
* just let them block (as in Thread.join). We also cannot just |
347 |
> |
* reassign the joiner's run-time stack with another and replace |
348 |
> |
* it later, which would be a form of "continuation", that even if |
349 |
> |
* possible is not necessarily a good idea since we sometimes need |
350 |
> |
* both an unblocked task and its continuation to progress. |
351 |
> |
* Instead we combine two tactics: |
352 |
> |
* |
353 |
> |
* Helping: Arranging for the joiner to execute some task that it |
354 |
> |
* would be running if the steal had not occurred. |
355 |
> |
* |
356 |
> |
* Compensating: Unless there are already enough live threads, |
357 |
> |
* method tryCompensate() may create or re-activate a spare |
358 |
> |
* thread to compensate for blocked joiners until they unblock. |
359 |
> |
* |
360 |
> |
* A third form (implemented in tryRemoveAndExec and |
361 |
> |
* tryPollForAndExec) amounts to helping a hypothetical |
362 |
> |
* compensator: If we can readily tell that a possible action of a |
363 |
> |
* compensator is to steal and execute the task being joined, the |
364 |
> |
* joining thread can do so directly, without the need for a |
365 |
> |
* compensation thread (although at the expense of larger run-time |
366 |
> |
* stacks, but the tradeoff is typically worthwhile). |
367 |
> |
* |
368 |
> |
* The ManagedBlocker extension API can't use helping so relies |
369 |
> |
* only on compensation in method awaitBlocker. |
370 |
> |
* |
371 |
> |
* The algorithm in tryHelpStealer entails a form of "linear" |
372 |
> |
* helping: Each worker records (in field currentSteal) the most |
373 |
> |
* recent task it stole from some other worker. Plus, it records |
374 |
> |
* (in field currentJoin) the task it is currently actively |
375 |
> |
* joining. Method tryHelpStealer uses these markers to try to |
376 |
> |
* find a worker to help (i.e., steal back a task from and execute |
377 |
> |
* it) that could hasten completion of the actively joined task. |
378 |
> |
* In essence, the joiner executes a task that would be on its own |
379 |
> |
* local deque had the to-be-joined task not been stolen. This may |
380 |
> |
* be seen as a conservative variant of the approach in Wagner & |
381 |
> |
* Calder "Leapfrogging: a portable technique for implementing |
382 |
> |
* efficient futures" SIGPLAN Notices, 1993 |
383 |
> |
* (http://portal.acm.org/citation.cfm?id=155354). It differs in |
384 |
> |
* that: (1) We only maintain dependency links across workers upon |
385 |
> |
* steals, rather than use per-task bookkeeping. This sometimes |
386 |
> |
* requires a linear scan of workers array to locate stealers, but |
387 |
> |
* often doesn't because stealers leave hints (that may become |
388 |
> |
* stale/wrong) of where to locate them. A stealHint is only a |
389 |
> |
* hint because a worker might have had multiple steals and the |
390 |
> |
* hint records only one of them (usually the most current). |
391 |
> |
* Hinting isolates cost to when it is needed, rather than adding |
392 |
> |
* to per-task overhead. (2) It is "shallow", ignoring nesting |
393 |
> |
* and potentially cyclic mutual steals. (3) It is intentionally |
394 |
> |
* racy: field currentJoin is updated only while actively joining, |
395 |
> |
* which means that we miss links in the chain during long-lived |
396 |
> |
* tasks, GC stalls etc (which is OK since blocking in such cases |
397 |
> |
* is usually a good idea). (4) We bound the number of attempts |
398 |
> |
* to find work (see MAX_HELP_DEPTH) and fall back to suspending |
399 |
> |
* the worker and if necessary replacing it with another. |
400 |
> |
* |
401 |
> |
* It is impossible to keep exactly the target parallelism number |
402 |
> |
* of threads running at any given time. Determining the |
403 |
> |
* existence of conservatively safe helping targets, the |
404 |
> |
* availability of already-created spares, and the apparent need |
405 |
> |
* to create new spares are all racy, so we rely on multiple |
406 |
> |
* retries of each. Currently, in keeping with on-demand |
407 |
> |
* signalling policy, we compensate only if blocking would leave |
408 |
> |
* less than one active (non-waiting, non-blocked) worker. |
409 |
> |
* Additionally, to avoid some false alarms due to GC, lagging |
410 |
> |
* counters, system activity, etc, compensated blocking for joins |
411 |
> |
* is only attempted after rechecks stabilize in |
412 |
> |
* ForkJoinTask.awaitJoin. (Retries are interspersed with |
413 |
> |
* Thread.yield, for good citizenship.) |
414 |
> |
* |
415 |
> |
* Style notes: There is a lot of representation-level coupling |
416 |
> |
* among classes ForkJoinPool, ForkJoinWorkerThread, and |
417 |
> |
* ForkJoinTask. The fields of WorkQueue maintain data structures |
418 |
> |
* managed by ForkJoinPool, so are directly accessed. There is |
419 |
> |
* little point trying to reduce this, since any associated future |
420 |
> |
* changes in representations will need to be accompanied by |
421 |
> |
* algorithmic changes anyway. All together, these low-level |
422 |
> |
* implementation choices produce as much as a factor of 4 |
423 |
> |
* performance improvement compared to naive implementations, and |
424 |
> |
* enable the processing of billions of tasks per second, at the |
425 |
> |
* expense of some ugliness. |
426 |
> |
* |
427 |
> |
* Methods signalWork() and scan() are the main bottlenecks, so are |
428 |
> |
* especially heavily micro-optimized/mangled. There are lots of |
429 |
> |
* inline assignments (of form "while ((local = field) != 0)") |
430 |
> |
* which are usually the simplest way to ensure the required read |
431 |
> |
* orderings (which are sometimes critical). This leads to a |
432 |
> |
* "C"-like style of listing declarations of these locals at the |
433 |
> |
* heads of methods or blocks. There are several occurrences of |
434 |
> |
* the unusual "do {} while (!cas...)" which is the simplest way |
435 |
> |
* to force an update of a CAS'ed variable. There are also other |
436 |
> |
* coding oddities that help some methods perform reasonably even |
437 |
> |
* when interpreted (not compiled). |
438 |
> |
* |
439 |
> |
* The order of declarations in this file is: |
440 |
> |
* (1) statics |
441 |
> |
* (2) fields (along with constants used when unpacking some of |
442 |
> |
* them), listed in an order that tends to reduce contention |
443 |
> |
* among them a bit under most JVMs; |
444 |
> |
* (3) nested classes |
445 |
> |
* (4) internal control methods |
446 |
> |
* (5) callbacks and other support for ForkJoinTask methods |
447 |
> |
* (6) exported methods (plus a few little helpers) |
448 |
> |
* (7) static block initializing all statics in a minimally |
449 |
> |
* dependent order. |
450 |
> |
*/ |
451 |
> |
|
452 |
> |
/** |
453 |
> |
* Factory for creating new {@link ForkJoinWorkerThread}s. |
454 |
> |
* A {@code ForkJoinWorkerThreadFactory} must be defined and used |
455 |
> |
* for {@code ForkJoinWorkerThread} subclasses that extend base |
456 |
> |
* functionality or initialize threads with different contexts. |
457 |
|
*/ |
458 |
|
public static interface ForkJoinWorkerThreadFactory { |
459 |
|
/** |
460 |
|
* Returns a new worker thread operating in the given pool. |
461 |
|
* |
462 |
|
* @param pool the pool this thread works in |
463 |
< |
* @throws NullPointerException if pool is null; |
463 |
> |
* @throws NullPointerException if the pool is null |
464 |
|
*/ |
465 |
|
public ForkJoinWorkerThread newThread(ForkJoinPool pool); |
466 |
|
} |
467 |
|
|
468 |
|
/** |
469 |
< |
* Default ForkJoinWorkerThreadFactory implementation, creates a |
469 |
> |
* Default ForkJoinWorkerThreadFactory implementation; creates a |
470 |
|
* new ForkJoinWorkerThread. |
471 |
|
*/ |
472 |
< |
static class DefaultForkJoinWorkerThreadFactory |
472 |
> |
static class DefaultForkJoinWorkerThreadFactory |
473 |
|
implements ForkJoinWorkerThreadFactory { |
474 |
|
public ForkJoinWorkerThread newThread(ForkJoinPool pool) { |
475 |
< |
try { |
97 |
< |
return new ForkJoinWorkerThread(pool); |
98 |
< |
} catch (OutOfMemoryError oom) { |
99 |
< |
return null; |
100 |
< |
} |
475 |
> |
return new ForkJoinWorkerThread(pool); |
476 |
|
} |
477 |
|
} |
478 |
|
|
481 |
|
* overridden in ForkJoinPool constructors. |
482 |
|
*/ |
483 |
|
public static final ForkJoinWorkerThreadFactory |
484 |
< |
defaultForkJoinWorkerThreadFactory = |
110 |
< |
new DefaultForkJoinWorkerThreadFactory(); |
484 |
> |
defaultForkJoinWorkerThreadFactory; |
485 |
|
|
486 |
|
/** |
487 |
|
* Permission required for callers of methods that may start or |
488 |
|
* kill threads. |
489 |
|
*/ |
490 |
< |
private static final RuntimePermission modifyThreadPermission = |
117 |
< |
new RuntimePermission("modifyThread"); |
490 |
> |
private static final RuntimePermission modifyThreadPermission; |
491 |
|
|
492 |
|
/** |
493 |
|
* If there is a security manager, makes sure caller has |
502 |
|
/** |
503 |
|
* Generator for assigning sequence numbers as pool names. |
504 |
|
*/ |
505 |
< |
private static final AtomicInteger poolNumberGenerator = |
133 |
< |
new AtomicInteger(); |
505 |
> |
private static final AtomicInteger poolNumberGenerator; |
506 |
|
|
507 |
|
/** |
508 |
< |
* Array holding all worker threads in the pool. Initialized upon |
509 |
< |
* first use. Array size must be a power of two. Updates and |
510 |
< |
* replacements are protected by workerLock, but it is always kept |
511 |
< |
* in a consistent enough state to be randomly accessed without |
512 |
< |
* locking by workers performing work-stealing. |
508 |
> |
* Bits and masks for control variables |
509 |
> |
* |
510 |
> |
* Field ctl is a long packed with: |
511 |
> |
* AC: Number of active running workers minus target parallelism (16 bits) |
512 |
> |
* TC: Number of total workers minus target parallelism (16 bits) |
513 |
> |
* ST: true if pool is terminating (1 bit) |
514 |
> |
* EC: the wait count of top waiting thread (15 bits) |
515 |
> |
* ID: ~(poolIndex >>> 1) of top of Treiber stack of waiters (16 bits) |
516 |
> |
* |
517 |
> |
* When convenient, we can extract the upper 32 bits of counts and |
518 |
> |
* the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e = |
519 |
> |
* (int)ctl. The ec field is never accessed alone, but always |
520 |
> |
* together with id and st. The offsets of counts by the target |
521 |
> |
* parallelism and the positionings of fields makes it possible to |
522 |
> |
* perform the most common checks via sign tests of fields: When |
523 |
> |
* ac is negative, there are not enough active workers, when tc is |
524 |
> |
* negative, there are not enough total workers, when id is |
525 |
> |
* negative, there is at least one waiting worker, and when e is |
526 |
> |
* negative, the pool is terminating. To deal with these possibly |
527 |
> |
* negative fields, we use casts in and out of "short" and/or |
528 |
> |
* signed shifts to maintain signedness. |
529 |
> |
* |
530 |
> |
* When a thread is queued (inactivated), its eventCount field is |
531 |
> |
* negative, which is the only way to tell if a worker is |
532 |
> |
* prevented from executing tasks, even though it must continue to |
533 |
> |
* scan for them to avoid queuing races. |
534 |
> |
* |
535 |
> |
* Field runState is an int packed with: |
536 |
> |
* SHUTDOWN: true if shutdown is enabled (1 bit) |
537 |
> |
* SEQ: a sequence number updated upon (de)registering workers (15 bits) |
538 |
> |
* MASK: mask (power of 2 - 1) covering all registered poolIndexes (16 bits) |
539 |
> |
* |
540 |
> |
* The combination of mask and sequence number enables simple |
541 |
> |
* consistency checks: Staleness of read-only operations on the |
542 |
> |
* workers and queues arrays can be checked by comparing runState |
543 |
> |
* before vs after the reads. The low 16 bits (i.e, anding with |
544 |
> |
* SMASK) hold the smallest power of two covering all worker |
545 |
> |
* indices, minus one. The mask for queues (vs workers) is twice |
546 |
> |
* this value plus 1. |
547 |
> |
*/ |
548 |
> |
|
549 |
> |
// bit positions/shifts for fields |
550 |
> |
private static final int AC_SHIFT = 48; |
551 |
> |
private static final int TC_SHIFT = 32; |
552 |
> |
private static final int ST_SHIFT = 31; |
553 |
> |
private static final int EC_SHIFT = 16; |
554 |
> |
|
555 |
> |
// bounds |
556 |
> |
private static final int MAX_ID = 0x7fff; // max poolIndex |
557 |
> |
private static final int SMASK = 0xffff; // mask short bits |
558 |
> |
private static final int SHORT_SIGN = 1 << 15; |
559 |
> |
private static final int INT_SIGN = 1 << 31; |
560 |
> |
|
561 |
> |
// masks |
562 |
> |
private static final long STOP_BIT = 0x0001L << ST_SHIFT; |
563 |
> |
private static final long AC_MASK = ((long)SMASK) << AC_SHIFT; |
564 |
> |
private static final long TC_MASK = ((long)SMASK) << TC_SHIFT; |
565 |
> |
|
566 |
> |
// units for incrementing and decrementing |
567 |
> |
private static final long TC_UNIT = 1L << TC_SHIFT; |
568 |
> |
private static final long AC_UNIT = 1L << AC_SHIFT; |
569 |
> |
|
570 |
> |
// masks and units for dealing with u = (int)(ctl >>> 32) |
571 |
> |
private static final int UAC_SHIFT = AC_SHIFT - 32; |
572 |
> |
private static final int UTC_SHIFT = TC_SHIFT - 32; |
573 |
> |
private static final int UAC_MASK = SMASK << UAC_SHIFT; |
574 |
> |
private static final int UTC_MASK = SMASK << UTC_SHIFT; |
575 |
> |
private static final int UAC_UNIT = 1 << UAC_SHIFT; |
576 |
> |
private static final int UTC_UNIT = 1 << UTC_SHIFT; |
577 |
> |
|
578 |
> |
// masks and units for dealing with e = (int)ctl |
579 |
> |
private static final int E_MASK = 0x7fffffff; // no STOP_BIT |
580 |
> |
private static final int E_SEQ = 1 << EC_SHIFT; |
581 |
> |
|
582 |
> |
// runState bits |
583 |
> |
private static final int SHUTDOWN = 1 << 31; |
584 |
> |
private static final int RS_SEQ = 1 << 16; |
585 |
> |
private static final int RS_SEQ_MASK = 0x7fff0000; |
586 |
> |
|
587 |
> |
// access mode for WorkQueue |
588 |
> |
static final int LIFO_QUEUE = 0; |
589 |
> |
static final int FIFO_QUEUE = 1; |
590 |
> |
static final int SHARED_QUEUE = -1; |
591 |
> |
|
592 |
> |
/** |
593 |
> |
* The wakeup interval (in nanoseconds) for a worker waiting for a |
594 |
> |
* task when the pool is quiescent to instead try to shrink the |
595 |
> |
* number of workers. The exact value does not matter too |
596 |
> |
* much. It must be short enough to release resources during |
597 |
> |
* sustained periods of idleness, but not so short that threads |
598 |
> |
* are continually re-created. |
599 |
> |
*/ |
600 |
> |
private static final long SHRINK_RATE = |
601 |
> |
4L * 1000L * 1000L * 1000L; // 4 seconds |
602 |
> |
|
603 |
> |
/** |
604 |
> |
* The timeout value for attempted shrinkage, includes |
605 |
> |
* some slop to cope with system timer imprecision. |
606 |
> |
*/ |
607 |
> |
private static final long SHRINK_TIMEOUT = SHRINK_RATE - (SHRINK_RATE / 10); |
608 |
> |
|
609 |
> |
/** |
610 |
> |
* The maximum stolen->joining link depth allowed in tryHelpStealer. |
611 |
> |
* Depths for legitimate chains are unbounded, but we use a fixed |
612 |
> |
* constant to avoid (otherwise unchecked) cycles and to bound |
613 |
> |
* staleness of traversal parameters at the expense of sometimes |
614 |
> |
* blocking when we could be helping. |
615 |
|
*/ |
616 |
< |
volatile ForkJoinWorkerThread[] workers; |
616 |
> |
private static final int MAX_HELP_DEPTH = 16; |
617 |
|
|
618 |
< |
/** |
619 |
< |
* Lock protecting access to workers. |
618 |
> |
/* |
619 |
> |
* Field layout order in this class tends to matter more than one |
620 |
> |
* would like. Runtime layout order is only loosely related to |
621 |
> |
* declaration order and may differ across JVMs, but the following |
622 |
> |
* empirically works OK on current JVMs. |
623 |
> |
*/ |
624 |
> |
|
625 |
> |
volatile long ctl; // main pool control |
626 |
> |
final int parallelism; // parallelism level |
627 |
> |
final int localMode; // per-worker scheduling mode |
628 |
> |
int nextPoolIndex; // hint used in registerWorker |
629 |
> |
volatile int runState; // shutdown status, seq, and mask |
630 |
> |
WorkQueue[] workQueues; // main registry |
631 |
> |
final ReentrantLock lock; // for registration |
632 |
> |
final Condition termination; // for awaitTermination |
633 |
> |
final ForkJoinWorkerThreadFactory factory; // factory for new workers |
634 |
> |
final Thread.UncaughtExceptionHandler ueh; // per-worker UEH |
635 |
> |
final AtomicLong stealCount; // collect counts when terminated |
636 |
> |
final AtomicInteger nextWorkerNumber; // to create worker name string |
637 |
> |
final String workerNamePrefix; // Prefix for assigning worker names |
638 |
> |
|
639 |
> |
/** |
640 |
> |
* Queues supporting work-stealing as well as external task |
641 |
> |
* submission. See above for main rationale and algorithms. |
642 |
> |
* Implementation relies heavily on "Unsafe" intrinsics |
643 |
> |
* and selective use of "volatile": |
644 |
> |
* |
645 |
> |
* Field "base" is the index (mod array.length) of the least valid |
646 |
> |
* queue slot, which is always the next position to steal (poll) |
647 |
> |
* from if nonempty. Reads and writes require volatile orderings |
648 |
> |
* but not CAS, because updates are only performed after slot |
649 |
> |
* CASes. |
650 |
> |
* |
651 |
> |
* Field "top" is the index (mod array.length) of the next queue |
652 |
> |
* slot to push to or pop from. It is written only by owner thread |
653 |
> |
* for push, or under lock for trySharedPush, and accessed by |
654 |
> |
* other threads only after reading (volatile) base. Both top and |
655 |
> |
* base are allowed to wrap around on overflow, but (top - base) |
656 |
> |
* (or more commonly -(base - top) to force volatile read of base |
657 |
> |
* before top) still estimates size. |
658 |
> |
* |
659 |
> |
* The array slots are read and written using the emulation of |
660 |
> |
* volatiles/atomics provided by Unsafe. Insertions must in |
661 |
> |
* general use putOrderedObject as a form of releasing store to |
662 |
> |
* ensure that all writes to the task object are ordered before |
663 |
> |
* its publication in the queue. (Although we can avoid one case |
664 |
> |
* of this when locked in trySharedPush.) All removals entail a |
665 |
> |
* CAS to null. The array is always a power of two. To ensure |
666 |
> |
* safety of Unsafe array operations, all accesses perform |
667 |
> |
* explicit null checks and implicit bounds checks via |
668 |
> |
* power-of-two masking. |
669 |
> |
* |
670 |
> |
* In addition to basic queuing support, this class contains |
671 |
> |
* fields described elsewhere to control execution. It turns out |
672 |
> |
* to work better memory-layout-wise to include them in this |
673 |
> |
* class rather than a separate class. |
674 |
> |
* |
675 |
> |
* Performance on most platforms is very sensitive to placement of |
676 |
> |
* instances of both WorkQueues and their arrays -- we absolutely |
677 |
> |
* do not want multiple WorkQueue instances or multiple queue |
678 |
> |
* arrays sharing cache lines. (It would be best for queue objects |
679 |
> |
* and their arrays to share, but there is nothing available to |
680 |
> |
* help arrange that). Unfortunately, because they are recorded |
681 |
> |
* in a common array, WorkQueue instances are often moved to be |
682 |
> |
* adjacent by garbage collectors. To reduce impact, we use field |
683 |
> |
* padding that works OK on common platforms; this effectively |
684 |
> |
* trades off slightly slower average field access for the sake of |
685 |
> |
* avoiding really bad worst-case access. (Until better JVM |
686 |
> |
* support is in place, this padding is dependent on transient |
687 |
> |
* properties of JVM field layout rules.) We also take care in |
688 |
> |
* allocating and sizing and resizing the array. Non-shared queue |
689 |
> |
* arrays are initialized (via method growArray) by workers before |
690 |
> |
* use. Others are allocated on first use. |
691 |
|
*/ |
692 |
< |
private final ReentrantLock workerLock; |
692 |
> |
static final class WorkQueue { |
693 |
> |
/** |
694 |
> |
* Capacity of work-stealing queue array upon initialization. |
695 |
> |
* Must be a power of two; at least 4, but set larger to |
696 |
> |
* reduce cacheline sharing among queues. |
697 |
> |
*/ |
698 |
> |
static final int INITIAL_QUEUE_CAPACITY = 1 << 8; |
699 |
|
|
700 |
< |
/** |
701 |
< |
* Condition for awaitTermination. |
702 |
< |
*/ |
703 |
< |
private final Condition termination; |
700 |
> |
/** |
701 |
> |
* Maximum size for queue arrays. Must be a power of two less |
702 |
> |
* than or equal to 1 << (31 - width of array entry) to ensure |
703 |
> |
* lack of wraparound of index calculations, but defined to a |
704 |
> |
* value a bit less than this to help users trap runaway |
705 |
> |
* programs before saturating systems. |
706 |
> |
*/ |
707 |
> |
static final int MAXIMUM_QUEUE_CAPACITY = 1 << 26; // 64M |
708 |
|
|
709 |
< |
/** |
710 |
< |
* The uncaught exception handler used when any worker |
711 |
< |
* abrupty terminates |
712 |
< |
*/ |
713 |
< |
private Thread.UncaughtExceptionHandler ueh; |
709 |
> |
volatile long totalSteals; // cumulative number of steals |
710 |
> |
int seed; // for random scanning; initialize nonzero |
711 |
> |
volatile int eventCount; // encoded inactivation count; < 0 if inactive |
712 |
> |
int nextWait; // encoded record of next event waiter |
713 |
> |
int rescans; // remaining scans until block |
714 |
> |
int nsteals; // top-level task executions since last idle |
715 |
> |
final int mode; // lifo, fifo, or shared |
716 |
> |
int poolIndex; // index of this queue in pool (or 0) |
717 |
> |
int stealHint; // index of most recent known stealer |
718 |
> |
volatile int runState; // 1: locked, -1: terminate; else 0 |
719 |
> |
volatile int base; // index of next slot for poll |
720 |
> |
int top; // index of next slot for push |
721 |
> |
ForkJoinTask<?>[] array; // the elements (initially unallocated) |
722 |
> |
final ForkJoinWorkerThread owner; // owning thread or null if shared |
723 |
> |
volatile Thread parker; // == owner during call to park; else null |
724 |
> |
ForkJoinTask<?> currentJoin; // task being joined in awaitJoin |
725 |
> |
ForkJoinTask<?> currentSteal; // current non-local task being executed |
726 |
> |
// Heuristic padding to ameliorate unfortunate memory placements |
727 |
> |
Object p00, p01, p02, p03, p04, p05, p06, p07, p08, p09, p0a; |
728 |
> |
|
729 |
> |
WorkQueue(ForkJoinWorkerThread owner, int mode) { |
730 |
> |
this.owner = owner; |
731 |
> |
this.mode = mode; |
732 |
> |
// Place indices in the center of array (that is not yet allocated) |
733 |
> |
base = top = INITIAL_QUEUE_CAPACITY >>> 1; |
734 |
> |
} |
735 |
|
|
736 |
< |
/** |
737 |
< |
* Creation factory for worker threads. |
738 |
< |
*/ |
739 |
< |
private final ForkJoinWorkerThreadFactory factory; |
736 |
> |
/** |
737 |
> |
* Returns number of tasks in the queue. |
738 |
> |
*/ |
739 |
> |
final int queueSize() { |
740 |
> |
int n = base - top; // non-owner callers must read base first |
741 |
> |
return (n >= 0) ? 0 : -n; |
742 |
> |
} |
743 |
|
|
744 |
< |
/** |
745 |
< |
* Head of stack of threads that were created to maintain |
746 |
< |
* parallelism when other threads blocked, but have since |
747 |
< |
* suspended when the parallelism level rose. |
748 |
< |
*/ |
749 |
< |
private volatile WaitQueueNode spareStack; |
744 |
> |
/** |
745 |
> |
* Pushes a task. Call only by owner in unshared queues. |
746 |
> |
* |
747 |
> |
* @param task the task. Caller must ensure non-null. |
748 |
> |
* @param p if non-null, pool to signal if necessary |
749 |
> |
* @throw RejectedExecutionException if array cannot be resized |
750 |
> |
*/ |
751 |
> |
final void push(ForkJoinTask<?> task, ForkJoinPool p) { |
752 |
> |
ForkJoinTask<?>[] a; |
753 |
> |
int s = top, m, n; |
754 |
> |
if ((a = array) != null) { // ignore if queue removed |
755 |
> |
U.putOrderedObject |
756 |
> |
(a, (((m = a.length - 1) & s) << ASHIFT) + ABASE, task); |
757 |
> |
if ((n = (top = s + 1) - base) <= 2) { |
758 |
> |
if (p != null) |
759 |
> |
p.signalWork(); |
760 |
> |
} |
761 |
> |
else if (n >= m) |
762 |
> |
growArray(true); |
763 |
> |
} |
764 |
> |
} |
765 |
|
|
766 |
< |
/** |
767 |
< |
* Sum of per-thread steal counts, updated only when threads are |
768 |
< |
* idle or terminating. |
769 |
< |
*/ |
770 |
< |
private final AtomicLong stealCount; |
766 |
> |
/** |
767 |
> |
* Pushes a task if lock is free and array is either big |
768 |
> |
* enough or can be resized to be big enough. |
769 |
> |
* |
770 |
> |
* @param task the task. Caller must ensure non-null. |
771 |
> |
* @return true if submitted |
772 |
> |
*/ |
773 |
> |
final boolean trySharedPush(ForkJoinTask<?> task) { |
774 |
> |
boolean submitted = false; |
775 |
> |
if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) { |
776 |
> |
ForkJoinTask<?>[] a = array; |
777 |
> |
int s = top, n = s - base; |
778 |
> |
try { |
779 |
> |
if ((a != null && n < a.length - 1) || |
780 |
> |
(a = growArray(false)) != null) { // must presize |
781 |
> |
int j = (((a.length - 1) & s) << ASHIFT) + ABASE; |
782 |
> |
U.putObject(a, (long)j, task); // don't need "ordered" |
783 |
> |
top = s + 1; |
784 |
> |
submitted = true; |
785 |
> |
} |
786 |
> |
} finally { |
787 |
> |
runState = 0; // unlock |
788 |
> |
} |
789 |
> |
} |
790 |
> |
return submitted; |
791 |
> |
} |
792 |
|
|
793 |
< |
/** |
794 |
< |
* Queue for external submissions. |
795 |
< |
*/ |
796 |
< |
private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue; |
793 |
> |
/** |
794 |
> |
* Takes next task, if one exists, in FIFO order. |
795 |
> |
*/ |
796 |
> |
final ForkJoinTask<?> poll() { |
797 |
> |
ForkJoinTask<?>[] a; int b, i; |
798 |
> |
while ((b = base) - top < 0 && (a = array) != null && |
799 |
> |
(i = (a.length - 1) & b) >= 0) { |
800 |
> |
int j = (i << ASHIFT) + ABASE; |
801 |
> |
ForkJoinTask<?> t = (ForkJoinTask<?>)U.getObjectVolatile(a, j); |
802 |
> |
if (t != null && base == b && |
803 |
> |
U.compareAndSwapObject(a, j, t, null)) { |
804 |
> |
base = b + 1; |
805 |
> |
return t; |
806 |
> |
} |
807 |
> |
} |
808 |
> |
return null; |
809 |
> |
} |
810 |
|
|
811 |
< |
/** |
812 |
< |
* Head of Treiber stack for barrier sync. See below for explanation |
813 |
< |
*/ |
814 |
< |
private volatile WaitQueueNode syncStack; |
811 |
> |
/** |
812 |
> |
* Takes next task, if one exists, in LIFO order. |
813 |
> |
* Call only by owner in unshared queues. |
814 |
> |
*/ |
815 |
> |
final ForkJoinTask<?> pop() { |
816 |
> |
ForkJoinTask<?> t; int m; |
817 |
> |
ForkJoinTask<?>[] a = array; |
818 |
> |
if (a != null && (m = a.length - 1) >= 0) { |
819 |
> |
for (int s; (s = top - 1) - base >= 0;) { |
820 |
> |
int j = ((m & s) << ASHIFT) + ABASE; |
821 |
> |
if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) == null) |
822 |
> |
break; |
823 |
> |
if (U.compareAndSwapObject(a, j, t, null)) { |
824 |
> |
top = s; |
825 |
> |
return t; |
826 |
> |
} |
827 |
> |
} |
828 |
> |
} |
829 |
> |
return null; |
830 |
> |
} |
831 |
|
|
832 |
< |
/** |
833 |
< |
* The count for event barrier |
834 |
< |
*/ |
835 |
< |
private volatile long eventCount; |
832 |
> |
/** |
833 |
> |
* Takes next task, if one exists, in order specified by mode. |
834 |
> |
*/ |
835 |
> |
final ForkJoinTask<?> nextLocalTask() { |
836 |
> |
return mode == 0 ? pop() : poll(); |
837 |
> |
} |
838 |
|
|
839 |
< |
/** |
840 |
< |
* Pool number, just for assigning useful names to worker threads |
841 |
< |
*/ |
842 |
< |
private final int poolNumber; |
839 |
> |
/** |
840 |
> |
* Returns next task, if one exists, in order specified by mode. |
841 |
> |
*/ |
842 |
> |
final ForkJoinTask<?> peek() { |
843 |
> |
ForkJoinTask<?>[] a = array; int m; |
844 |
> |
if (a == null || (m = a.length - 1) < 0) |
845 |
> |
return null; |
846 |
> |
int i = mode == 0 ? top - 1 : base; |
847 |
> |
int j = ((i & m) << ASHIFT) + ABASE; |
848 |
> |
return (ForkJoinTask<?>)U.getObjectVolatile(a, j); |
849 |
> |
} |
850 |
> |
|
851 |
> |
/** |
852 |
> |
* Returns task at index b if b is current base of queue. |
853 |
> |
*/ |
854 |
> |
final ForkJoinTask<?> pollAt(int b) { |
855 |
> |
ForkJoinTask<?>[] a; int i; |
856 |
> |
ForkJoinTask<?> task = null; |
857 |
> |
if ((a = array) != null && (i = ((a.length - 1) & b)) >= 0) { |
858 |
> |
int j = (i << ASHIFT) + ABASE; |
859 |
> |
ForkJoinTask<?> t = (ForkJoinTask<?>)U.getObjectVolatile(a, j); |
860 |
> |
if (t != null && base == b && |
861 |
> |
U.compareAndSwapObject(a, j, t, null)) { |
862 |
> |
base = b + 1; |
863 |
> |
task = t; |
864 |
> |
} |
865 |
> |
} |
866 |
> |
return task; |
867 |
> |
} |
868 |
> |
|
869 |
> |
/** |
870 |
> |
* Pops the given task only if it is at the current top. |
871 |
> |
*/ |
872 |
> |
final boolean tryUnpush(ForkJoinTask<?> t) { |
873 |
> |
ForkJoinTask<?>[] a; int s; |
874 |
> |
if ((a = array) != null && (s = top) != base && |
875 |
> |
U.compareAndSwapObject |
876 |
> |
(a, (((a.length - 1) & --s) << ASHIFT) + ABASE, t, null)) { |
877 |
> |
top = s; |
878 |
> |
return true; |
879 |
> |
} |
880 |
> |
return false; |
881 |
> |
} |
882 |
> |
|
883 |
> |
/** |
884 |
> |
* Polls the given task only if it is at the current base. |
885 |
> |
*/ |
886 |
> |
final boolean pollFor(ForkJoinTask<?> task) { |
887 |
> |
ForkJoinTask<?>[] a; int b, i; |
888 |
> |
if ((b = base) - top < 0 && (a = array) != null && |
889 |
> |
(i = (a.length - 1) & b) >= 0) { |
890 |
> |
int j = (i << ASHIFT) + ABASE; |
891 |
> |
if (U.getObjectVolatile(a, j) == task && base == b && |
892 |
> |
U.compareAndSwapObject(a, j, task, null)) { |
893 |
> |
base = b + 1; |
894 |
> |
return true; |
895 |
> |
} |
896 |
> |
} |
897 |
> |
return false; |
898 |
> |
} |
899 |
> |
|
900 |
> |
/** |
901 |
> |
* If present, removes from queue and executes the given task, or |
902 |
> |
* any other cancelled task. Returns (true) immediately on any CAS |
903 |
> |
* or consistency check failure so caller can retry. |
904 |
> |
* |
905 |
> |
* @return false if no progress can be made |
906 |
> |
*/ |
907 |
> |
final boolean tryRemoveAndExec(ForkJoinTask<?> task) { |
908 |
> |
boolean removed = false, empty = true, progress = true; |
909 |
> |
ForkJoinTask<?>[] a; int m, s, b, n; |
910 |
> |
if ((a = array) != null && (m = a.length - 1) >= 0 && |
911 |
> |
(n = (s = top) - (b = base)) > 0) { |
912 |
> |
for (ForkJoinTask<?> t;;) { // traverse from s to b |
913 |
> |
int j = ((--s & m) << ASHIFT) + ABASE; |
914 |
> |
t = (ForkJoinTask<?>)U.getObjectVolatile(a, j); |
915 |
> |
if (t == null) // inconsistent length |
916 |
> |
break; |
917 |
> |
else if (t == task) { |
918 |
> |
if (s + 1 == top) { // pop |
919 |
> |
if (!U.compareAndSwapObject(a, j, task, null)) |
920 |
> |
break; |
921 |
> |
top = s; |
922 |
> |
removed = true; |
923 |
> |
} |
924 |
> |
else if (base == b) // replace with proxy |
925 |
> |
removed = U.compareAndSwapObject(a, j, task, |
926 |
> |
new EmptyTask()); |
927 |
> |
break; |
928 |
> |
} |
929 |
> |
else if (t.status >= 0) |
930 |
> |
empty = false; |
931 |
> |
else if (s + 1 == top) { // pop and throw away |
932 |
> |
if (U.compareAndSwapObject(a, j, t, null)) |
933 |
> |
top = s; |
934 |
> |
break; |
935 |
> |
} |
936 |
> |
if (--n == 0) { |
937 |
> |
if (!empty && base == b) |
938 |
> |
progress = false; |
939 |
> |
break; |
940 |
> |
} |
941 |
> |
} |
942 |
> |
} |
943 |
> |
if (removed) |
944 |
> |
task.doExec(); |
945 |
> |
return progress; |
946 |
> |
} |
947 |
> |
|
948 |
> |
/** |
949 |
> |
* Initializes or doubles the capacity of array. Call either |
950 |
> |
* by owner or with lock held -- it is OK for base, but not |
951 |
> |
* top, to move while resizings are in progress. |
952 |
> |
* |
953 |
> |
* @param rejectOnFailure if true, throw exception if capacity |
954 |
> |
* exceeded (relayed ultimately to user); else return null. |
955 |
> |
*/ |
956 |
> |
final ForkJoinTask<?>[] growArray(boolean rejectOnFailure) { |
957 |
> |
ForkJoinTask<?>[] oldA = array; |
958 |
> |
int size = oldA != null ? oldA.length << 1 : INITIAL_QUEUE_CAPACITY; |
959 |
> |
if (size <= MAXIMUM_QUEUE_CAPACITY) { |
960 |
> |
int oldMask, t, b; |
961 |
> |
ForkJoinTask<?>[] a = array = new ForkJoinTask<?>[size]; |
962 |
> |
if (oldA != null && (oldMask = oldA.length - 1) >= 0 && |
963 |
> |
(t = top) - (b = base) > 0) { |
964 |
> |
int mask = size - 1; |
965 |
> |
do { |
966 |
> |
ForkJoinTask<?> x; |
967 |
> |
int oldj = ((b & oldMask) << ASHIFT) + ABASE; |
968 |
> |
int j = ((b & mask) << ASHIFT) + ABASE; |
969 |
> |
x = (ForkJoinTask<?>)U.getObjectVolatile(oldA, oldj); |
970 |
> |
if (x != null && |
971 |
> |
U.compareAndSwapObject(oldA, oldj, x, null)) |
972 |
> |
U.putObjectVolatile(a, j, x); |
973 |
> |
} while (++b != t); |
974 |
> |
} |
975 |
> |
return a; |
976 |
> |
} |
977 |
> |
else if (!rejectOnFailure) |
978 |
> |
return null; |
979 |
> |
else |
980 |
> |
throw new RejectedExecutionException("Queue capacity exceeded"); |
981 |
> |
} |
982 |
> |
|
983 |
> |
/** |
984 |
> |
* Removes and cancels all known tasks, ignoring any exceptions. |
985 |
> |
*/ |
986 |
> |
final void cancelAll() { |
987 |
> |
ForkJoinTask.cancelIgnoringExceptions(currentJoin); |
988 |
> |
ForkJoinTask.cancelIgnoringExceptions(currentSteal); |
989 |
> |
for (ForkJoinTask<?> t; (t = poll()) != null; ) |
990 |
> |
ForkJoinTask.cancelIgnoringExceptions(t); |
991 |
> |
} |
992 |
> |
|
993 |
> |
// Execution methods |
994 |
> |
|
995 |
> |
/** |
996 |
> |
* Removes and runs tasks until empty, using local mode |
997 |
> |
* ordering. |
998 |
> |
*/ |
999 |
> |
final void runLocalTasks() { |
1000 |
> |
if (base - top < 0) { |
1001 |
> |
for (ForkJoinTask<?> t; (t = nextLocalTask()) != null; ) |
1002 |
> |
t.doExec(); |
1003 |
> |
} |
1004 |
> |
} |
1005 |
> |
|
1006 |
> |
/** |
1007 |
> |
* Executes a top-level task and any local tasks remaining |
1008 |
> |
* after execution. |
1009 |
> |
* |
1010 |
> |
* @return true unless terminating |
1011 |
> |
*/ |
1012 |
> |
final boolean runTask(ForkJoinTask<?> t) { |
1013 |
> |
boolean alive = true; |
1014 |
> |
if (t != null) { |
1015 |
> |
currentSteal = t; |
1016 |
> |
t.doExec(); |
1017 |
> |
runLocalTasks(); |
1018 |
> |
++nsteals; |
1019 |
> |
currentSteal = null; |
1020 |
> |
} |
1021 |
> |
else if (runState < 0) // terminating |
1022 |
> |
alive = false; |
1023 |
> |
return alive; |
1024 |
> |
} |
1025 |
> |
|
1026 |
> |
/** |
1027 |
> |
* Executes a non-top-level (stolen) task. |
1028 |
> |
*/ |
1029 |
> |
final void runSubtask(ForkJoinTask<?> t) { |
1030 |
> |
if (t != null) { |
1031 |
> |
ForkJoinTask<?> ps = currentSteal; |
1032 |
> |
currentSteal = t; |
1033 |
> |
t.doExec(); |
1034 |
> |
currentSteal = ps; |
1035 |
> |
} |
1036 |
> |
} |
1037 |
> |
|
1038 |
> |
/** |
1039 |
> |
* Computes next value for random probes. Scans don't require |
1040 |
> |
* a very high quality generator, but also not a crummy one. |
1041 |
> |
* Marsaglia xor-shift is cheap and works well enough. Note: |
1042 |
> |
* This is manually inlined in several usages in ForkJoinPool |
1043 |
> |
* to avoid writes inside busy scan loops. |
1044 |
> |
*/ |
1045 |
> |
final int nextSeed() { |
1046 |
> |
int r = seed; |
1047 |
> |
r ^= r << 13; |
1048 |
> |
r ^= r >>> 17; |
1049 |
> |
r ^= r << 5; |
1050 |
> |
return seed = r; |
1051 |
> |
} |
1052 |
> |
|
1053 |
> |
// Unsafe mechanics |
1054 |
> |
private static final sun.misc.Unsafe U; |
1055 |
> |
private static final long RUNSTATE; |
1056 |
> |
private static final int ABASE; |
1057 |
> |
private static final int ASHIFT; |
1058 |
> |
static { |
1059 |
> |
int s; |
1060 |
> |
try { |
1061 |
> |
U = getUnsafe(); |
1062 |
> |
Class<?> k = WorkQueue.class; |
1063 |
> |
Class<?> ak = ForkJoinTask[].class; |
1064 |
> |
RUNSTATE = U.objectFieldOffset |
1065 |
> |
(k.getDeclaredField("runState")); |
1066 |
> |
ABASE = U.arrayBaseOffset(ak); |
1067 |
> |
s = U.arrayIndexScale(ak); |
1068 |
> |
} catch (Exception e) { |
1069 |
> |
throw new Error(e); |
1070 |
> |
} |
1071 |
> |
if ((s & (s-1)) != 0) |
1072 |
> |
throw new Error("data type scale not a power of two"); |
1073 |
> |
ASHIFT = 31 - Integer.numberOfLeadingZeros(s); |
1074 |
> |
} |
1075 |
> |
} |
1076 |
|
|
1077 |
|
/** |
1078 |
< |
* The maximum allowed pool size |
1078 |
> |
* Class for artificial tasks that are used to replace the target |
1079 |
> |
* of local joins if they are removed from an interior queue slot |
1080 |
> |
* in WorkQueue.tryRemoveAndExec. We don't need the proxy to |
1081 |
> |
* actually do anything beyond having a unique identity. |
1082 |
|
*/ |
1083 |
< |
private volatile int maxPoolSize; |
1083 |
> |
static final class EmptyTask extends ForkJoinTask<Void> { |
1084 |
> |
EmptyTask() { status = ForkJoinTask.NORMAL; } // force done |
1085 |
> |
public Void getRawResult() { return null; } |
1086 |
> |
public void setRawResult(Void x) {} |
1087 |
> |
public boolean exec() { return true; } |
1088 |
> |
} |
1089 |
|
|
1090 |
|
/** |
1091 |
< |
* The desired parallelism level, updated only under workerLock. |
1091 |
> |
* Per-thread records for (typically non-FJ) threads that submit |
1092 |
> |
* to pools. Cureently holds only psuedo-random seed / index that |
1093 |
> |
* is used to choose submission queues in method doSubmit. In the |
1094 |
> |
* future, this may incorporate a means to implement different |
1095 |
> |
* task rejection and resubmission policies. |
1096 |
|
*/ |
1097 |
< |
private volatile int parallelism; |
1097 |
> |
static final class Submitter { |
1098 |
> |
int seed; // seed for random submission queue selection |
1099 |
> |
|
1100 |
> |
// Heuristic padding to ameliorate unfortunate memory placements |
1101 |
> |
int p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, pa, pb, pc, pd, pe; |
1102 |
> |
|
1103 |
> |
Submitter() { |
1104 |
> |
// Use identityHashCode, forced negative, for seed |
1105 |
> |
seed = System.identityHashCode(Thread.currentThread()) | (1 << 31); |
1106 |
> |
} |
1107 |
> |
|
1108 |
> |
/** |
1109 |
> |
* Computes next value for random probes. Like method |
1110 |
> |
* WorkQueue.nextSeed, this is manually inlined in several |
1111 |
> |
* usages to avoid writes inside busy loops. |
1112 |
> |
*/ |
1113 |
> |
final int nextSeed() { |
1114 |
> |
int r = seed; |
1115 |
> |
r ^= r << 13; |
1116 |
> |
r ^= r >>> 17; |
1117 |
> |
return seed = r ^= r << 5; |
1118 |
> |
} |
1119 |
> |
} |
1120 |
> |
|
1121 |
> |
/** ThreadLocal class for Submitters */ |
1122 |
> |
static final class ThreadSubmitter extends ThreadLocal<Submitter> { |
1123 |
> |
public Submitter initialValue() { return new Submitter(); } |
1124 |
> |
} |
1125 |
|
|
1126 |
|
/** |
1127 |
< |
* True if use local fifo, not default lifo, for local polling |
1127 |
> |
* Per-thread submission bookeeping. Shared across all pools |
1128 |
> |
* to reduce ThreadLocal pollution and because random motion |
1129 |
> |
* to avoid contention in one pool is likely to hold for others. |
1130 |
|
*/ |
1131 |
< |
private volatile boolean locallyFifo; |
1131 |
> |
static final ThreadSubmitter submitters = new ThreadSubmitter(); |
1132 |
|
|
1133 |
|
/** |
1134 |
< |
* Holds number of total (i.e., created and not yet terminated) |
215 |
< |
* and running (i.e., not blocked on joins or other managed sync) |
216 |
< |
* threads, packed into one int to ensure consistent snapshot when |
217 |
< |
* making decisions about creating and suspending spare |
218 |
< |
* threads. Updated only by CAS. Note: CASes in |
219 |
< |
* updateRunningCount and preJoin running active count is in low |
220 |
< |
* word, so need to be modified if this changes |
1134 |
> |
* Top-level runloop for workers |
1135 |
|
*/ |
1136 |
< |
private volatile int workerCounts; |
1136 |
> |
final void runWorker(ForkJoinWorkerThread wt) { |
1137 |
> |
// Initialize queue array and seed in this thread |
1138 |
> |
WorkQueue w = wt.workQueue; |
1139 |
> |
w.growArray(false); |
1140 |
> |
// Same initial hash as Submitters |
1141 |
> |
w.seed = System.identityHashCode(Thread.currentThread()) | (1 << 31); |
1142 |
> |
|
1143 |
> |
do {} while (w.runTask(scan(w))); |
1144 |
> |
} |
1145 |
|
|
1146 |
< |
private static int totalCountOf(int s) { return s >>> 16; } |
225 |
< |
private static int runningCountOf(int s) { return s & shortMask; } |
226 |
< |
private static int workerCountsFor(int t, int r) { return (t << 16) + r; } |
1146 |
> |
// Creating, registering and deregistering workers |
1147 |
|
|
1148 |
|
/** |
1149 |
< |
* Add delta (which may be negative) to running count. This must |
230 |
< |
* be called before (with negative arg) and after (with positive) |
231 |
< |
* any managed synchronization (i.e., mainly, joins) |
232 |
< |
* @param delta the number to add |
1149 |
> |
* Tries to create and start a worker |
1150 |
|
*/ |
1151 |
< |
final void updateRunningCount(int delta) { |
1152 |
< |
int s; |
1153 |
< |
do;while (!casWorkerCounts(s = workerCounts, s + delta)); |
1151 |
> |
private void addWorker() { |
1152 |
> |
Throwable ex = null; |
1153 |
> |
ForkJoinWorkerThread w = null; |
1154 |
> |
try { |
1155 |
> |
if ((w = factory.newThread(this)) != null) { |
1156 |
> |
w.start(); |
1157 |
> |
return; |
1158 |
> |
} |
1159 |
> |
} catch (Throwable e) { |
1160 |
> |
ex = e; |
1161 |
> |
} |
1162 |
> |
deregisterWorker(w, ex); |
1163 |
|
} |
1164 |
|
|
1165 |
|
/** |
1166 |
< |
* Add delta (which may be negative) to both total and running |
1167 |
< |
* count. This must be called upon creation and termination of |
1168 |
< |
* worker threads. |
1169 |
< |
* @param delta the number to add |
1166 |
> |
* Callback from ForkJoinWorkerThread constructor to assign a |
1167 |
> |
* public name. This must be separate from registerWorker because |
1168 |
> |
* it is called during the "super" constructor call in |
1169 |
> |
* ForkJoinWorkerThread. |
1170 |
|
*/ |
1171 |
< |
private void updateWorkerCount(int delta) { |
1172 |
< |
int d = delta + (delta << 16); // add to both lo and hi parts |
1173 |
< |
int s; |
248 |
< |
do;while (!casWorkerCounts(s = workerCounts, s + d)); |
1171 |
> |
final String nextWorkerName() { |
1172 |
> |
return workerNamePrefix.concat |
1173 |
> |
(Integer.toString(nextWorkerNumber.addAndGet(1))); |
1174 |
|
} |
1175 |
|
|
1176 |
|
/** |
1177 |
< |
* Lifecycle control. High word contains runState, low word |
1178 |
< |
* contains the number of workers that are (probably) executing |
1179 |
< |
* tasks. This value is atomically incremented before a worker |
1180 |
< |
* gets a task to run, and decremented when worker has no tasks |
256 |
< |
* and cannot find any. These two fields are bundled together to |
257 |
< |
* support correct termination triggering. Note: activeCount |
258 |
< |
* CAS'es cheat by assuming active count is in low word, so need |
259 |
< |
* to be modified if this changes |
1177 |
> |
* Callback from ForkJoinWorkerThread constructor to establish and |
1178 |
> |
* record its WorkQueue. |
1179 |
> |
* |
1180 |
> |
* @param wt the worker thread |
1181 |
|
*/ |
1182 |
< |
private volatile int runControl; |
1183 |
< |
|
1184 |
< |
// RunState values. Order among values matters |
1185 |
< |
private static final int RUNNING = 0; |
1186 |
< |
private static final int SHUTDOWN = 1; |
1187 |
< |
private static final int TERMINATING = 2; |
1188 |
< |
private static final int TERMINATED = 3; |
1189 |
< |
|
1190 |
< |
private static int runStateOf(int c) { return c >>> 16; } |
1191 |
< |
private static int activeCountOf(int c) { return c & shortMask; } |
1192 |
< |
private static int runControlFor(int r, int a) { return (r << 16) + a; } |
1182 |
> |
final void registerWorker(ForkJoinWorkerThread wt) { |
1183 |
> |
WorkQueue w = wt.workQueue; |
1184 |
> |
ReentrantLock lock = this.lock; |
1185 |
> |
lock.lock(); |
1186 |
> |
try { |
1187 |
> |
int k = nextPoolIndex; |
1188 |
> |
WorkQueue[] ws = workQueues; |
1189 |
> |
if (ws != null) { // ignore on shutdown |
1190 |
> |
int n = ws.length; |
1191 |
> |
if (k < 0 || (k & 1) == 0 || k >= n || ws[k] != null) { |
1192 |
> |
for (k = 1; k < n && ws[k] != null; k += 2) |
1193 |
> |
; // workers are at odd indices |
1194 |
> |
if (k >= n) // resize |
1195 |
> |
workQueues = ws = Arrays.copyOf(ws, n << 1); |
1196 |
> |
} |
1197 |
> |
w.poolIndex = k; |
1198 |
> |
w.eventCount = ~(k >>> 1) & SMASK; // Set up wait count |
1199 |
> |
ws[k] = w; // record worker |
1200 |
> |
nextPoolIndex = k + 2; |
1201 |
> |
int rs = runState; |
1202 |
> |
int m = rs & SMASK; // recalculate runState mask |
1203 |
> |
if (k > m) |
1204 |
> |
m = (m << 1) + 1; |
1205 |
> |
runState = (rs & SHUTDOWN) | ((rs + RS_SEQ) & RS_SEQ_MASK) | m; |
1206 |
> |
} |
1207 |
> |
} finally { |
1208 |
> |
lock.unlock(); |
1209 |
> |
} |
1210 |
> |
} |
1211 |
|
|
1212 |
|
/** |
1213 |
< |
* Try incrementing active count; fail on contention. Called by |
1214 |
< |
* workers before/during executing tasks. |
1215 |
< |
* @return true on success; |
1216 |
< |
*/ |
1217 |
< |
final boolean tryIncrementActiveCount() { |
1218 |
< |
int c = runControl; |
1219 |
< |
return casRunControl(c, c+1); |
1213 |
> |
* Final callback from terminating worker, as well as failure to |
1214 |
> |
* construct or start a worker in addWorker. Removes record of |
1215 |
> |
* worker from array, and adjusts counts. If pool is shutting |
1216 |
> |
* down, tries to complete termination. |
1217 |
> |
* |
1218 |
> |
* @param wt the worker thread or null if addWorker failed |
1219 |
> |
* @param ex the exception causing failure, or null if none |
1220 |
> |
*/ |
1221 |
> |
final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) { |
1222 |
> |
WorkQueue w = null; |
1223 |
> |
if (wt != null && (w = wt.workQueue) != null) { |
1224 |
> |
w.runState = -1; // ensure runState is set |
1225 |
> |
stealCount.getAndAdd(w.totalSteals + w.nsteals); |
1226 |
> |
int idx = w.poolIndex; |
1227 |
> |
ReentrantLock lock = this.lock; |
1228 |
> |
lock.lock(); |
1229 |
> |
try { // remove record from array |
1230 |
> |
WorkQueue[] ws = workQueues; |
1231 |
> |
if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w) |
1232 |
> |
ws[nextPoolIndex = idx] = null; |
1233 |
> |
} finally { |
1234 |
> |
lock.unlock(); |
1235 |
> |
} |
1236 |
> |
} |
1237 |
> |
|
1238 |
> |
long c; // adjust ctl counts |
1239 |
> |
do {} while (!U.compareAndSwapLong |
1240 |
> |
(this, CTL, c = ctl, (((c - AC_UNIT) & AC_MASK) | |
1241 |
> |
((c - TC_UNIT) & TC_MASK) | |
1242 |
> |
(c & ~(AC_MASK|TC_MASK))))); |
1243 |
> |
|
1244 |
> |
if (!tryTerminate(false) && w != null) { |
1245 |
> |
w.cancelAll(); // cancel remaining tasks |
1246 |
> |
if (w.array != null) // suppress signal if never ran |
1247 |
> |
signalWork(); // wake up or create replacement |
1248 |
> |
} |
1249 |
> |
|
1250 |
> |
if (ex != null) // rethrow |
1251 |
> |
U.throwException(ex); |
1252 |
|
} |
1253 |
|
|
1254 |
|
/** |
1255 |
< |
* Try decrementing active count; fail on contention. |
1256 |
< |
* Possibly trigger termination on success |
1257 |
< |
* Called by workers when they can't find tasks. |
1258 |
< |
* @return true on success |
1259 |
< |
*/ |
1260 |
< |
final boolean tryDecrementActiveCount() { |
1261 |
< |
int c = runControl; |
1262 |
< |
int nextc = c - 1; |
1263 |
< |
if (!casRunControl(c, nextc)) |
1264 |
< |
return false; |
1265 |
< |
if (canTerminateOnShutdown(nextc)) |
1266 |
< |
terminateOnShutdown(); |
1267 |
< |
return true; |
1255 |
> |
* Tries to add and register a new queue at the given index. |
1256 |
> |
* |
1257 |
> |
* @param idx the workQueues array index to register the queue |
1258 |
> |
* @return the queue, or null if could not add because could |
1259 |
> |
* not acquire lock or idx is unusable |
1260 |
> |
*/ |
1261 |
> |
private WorkQueue tryAddSharedQueue(int idx) { |
1262 |
> |
WorkQueue q = null; |
1263 |
> |
ReentrantLock lock = this.lock; |
1264 |
> |
if (idx >= 0 && (idx & 1) == 0 && !lock.isLocked()) { |
1265 |
> |
// create queue outside of lock but only if apparently free |
1266 |
> |
WorkQueue nq = new WorkQueue(null, SHARED_QUEUE); |
1267 |
> |
if (lock.tryLock()) { |
1268 |
> |
try { |
1269 |
> |
WorkQueue[] ws = workQueues; |
1270 |
> |
if (ws != null && idx < ws.length) { |
1271 |
> |
if ((q = ws[idx]) == null) { |
1272 |
> |
int rs; // update runState seq |
1273 |
> |
ws[idx] = q = nq; |
1274 |
> |
runState = (((rs = runState) & SHUTDOWN) | |
1275 |
> |
((rs + RS_SEQ) & ~SHUTDOWN)); |
1276 |
> |
} |
1277 |
> |
} |
1278 |
> |
} finally { |
1279 |
> |
lock.unlock(); |
1280 |
> |
} |
1281 |
> |
} |
1282 |
> |
} |
1283 |
> |
return q; |
1284 |
|
} |
1285 |
|
|
1286 |
+ |
// Maintaining ctl counts |
1287 |
+ |
|
1288 |
|
/** |
1289 |
< |
* Return true if argument represents zero active count and |
301 |
< |
* nonzero runstate, which is the triggering condition for |
302 |
< |
* terminating on shutdown. |
1289 |
> |
* Increments active count; mainly called upon return from blocking. |
1290 |
|
*/ |
1291 |
< |
private static boolean canTerminateOnShutdown(int c) { |
1292 |
< |
return ((c & -c) >>> 16) != 0; // i.e. least bit is nonzero runState bit |
1291 |
> |
final void incrementActiveCount() { |
1292 |
> |
long c; |
1293 |
> |
do {} while (!U.compareAndSwapLong(this, CTL, c = ctl, c + AC_UNIT)); |
1294 |
|
} |
1295 |
|
|
1296 |
|
/** |
1297 |
< |
* Transition run state to at least the given state. Return true |
310 |
< |
* if not already at least given state. |
1297 |
> |
* Activates or creates a worker. |
1298 |
|
*/ |
1299 |
< |
private boolean transitionRunStateTo(int state) { |
1300 |
< |
for (;;) { |
1301 |
< |
int c = runControl; |
1302 |
< |
if (runStateOf(c) >= state) |
1303 |
< |
return false; |
1304 |
< |
if (casRunControl(c, runControlFor(state, activeCountOf(c)))) |
1305 |
< |
return true; |
1299 |
> |
final void signalWork() { |
1300 |
> |
/* |
1301 |
> |
* The while condition is true if: (there is are too few total |
1302 |
> |
* workers OR there is at least one waiter) AND (there are too |
1303 |
> |
* few active workers OR the pool is terminating). The value |
1304 |
> |
* of e distinguishes the remaining cases: zero (no waiters) |
1305 |
> |
* for create, negative if terminating (in which case do |
1306 |
> |
* nothing), else release a waiter. The secondary checks for |
1307 |
> |
* release (non-null array etc) can fail if the pool begins |
1308 |
> |
* terminating after the test, and don't impose any added cost |
1309 |
> |
* because JVMs must perform null and bounds checks anyway. |
1310 |
> |
*/ |
1311 |
> |
long c; int e, u; |
1312 |
> |
while ((((e = (int)(c = ctl)) | (u = (int)(c >>> 32))) & |
1313 |
> |
(INT_SIGN|SHORT_SIGN)) == (INT_SIGN|SHORT_SIGN)) { |
1314 |
> |
WorkQueue[] ws = workQueues; int i; WorkQueue w; Thread p; |
1315 |
> |
if (e == 0) { // add a new worker |
1316 |
> |
if (U.compareAndSwapLong |
1317 |
> |
(this, CTL, c, (long)(((u + UTC_UNIT) & UTC_MASK) | |
1318 |
> |
((u + UAC_UNIT) & UAC_MASK)) << 32)) { |
1319 |
> |
addWorker(); |
1320 |
> |
break; |
1321 |
> |
} |
1322 |
> |
} |
1323 |
> |
else if (e > 0 && ws != null && |
1324 |
> |
(i = ((~e << 1) | 1) & SMASK) < ws.length && |
1325 |
> |
(w = ws[i]) != null && |
1326 |
> |
w.eventCount == (e | INT_SIGN)) { |
1327 |
> |
if (U.compareAndSwapLong |
1328 |
> |
(this, CTL, c, (((long)(w.nextWait & E_MASK)) | |
1329 |
> |
((long)(u + UAC_UNIT) << 32)))) { |
1330 |
> |
w.eventCount = (e + E_SEQ) & E_MASK; |
1331 |
> |
if ((p = w.parker) != null) |
1332 |
> |
U.unpark(p); // release a waiting worker |
1333 |
> |
break; |
1334 |
> |
} |
1335 |
> |
} |
1336 |
> |
else |
1337 |
> |
break; |
1338 |
|
} |
1339 |
|
} |
1340 |
|
|
1341 |
|
/** |
1342 |
< |
* Controls whether to add spares to maintain parallelism |
1343 |
< |
*/ |
1344 |
< |
private volatile boolean maintainsParallelism; |
1342 |
> |
* Tries to decrement active count (sometimes implicitly) and |
1343 |
> |
* possibly release or create a compensating worker in preparation |
1344 |
> |
* for blocking. Fails on contention or termination. |
1345 |
> |
* |
1346 |
> |
* @return true if the caller can block, else should recheck and retry |
1347 |
> |
*/ |
1348 |
> |
final boolean tryCompensate() { |
1349 |
> |
WorkQueue[] ws; WorkQueue w; Thread p; |
1350 |
> |
int pc = parallelism, e, u, ac, tc, i; |
1351 |
> |
long c = ctl; |
1352 |
> |
|
1353 |
> |
if ((e = (int)c) >= 0) { |
1354 |
> |
if ((ac = ((u = (int)(c >>> 32)) >> UAC_SHIFT)) <= 0 && |
1355 |
> |
e != 0 && (ws = workQueues) != null && |
1356 |
> |
(i = ((~e << 1) | 1) & SMASK) < ws.length && |
1357 |
> |
(w = ws[i]) != null) { |
1358 |
> |
if (w.eventCount == (e | INT_SIGN) && |
1359 |
> |
U.compareAndSwapLong |
1360 |
> |
(this, CTL, c, ((long)(w.nextWait & E_MASK) | |
1361 |
> |
(c & (AC_MASK|TC_MASK))))) { |
1362 |
> |
w.eventCount = (e + E_SEQ) & E_MASK; |
1363 |
> |
if ((p = w.parker) != null) |
1364 |
> |
U.unpark(p); |
1365 |
> |
return true; // release an idle worker |
1366 |
> |
} |
1367 |
> |
} |
1368 |
> |
else if ((tc = (short)(u >>> UTC_SHIFT)) >= 0 && ac + pc > 1) { |
1369 |
> |
long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK); |
1370 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) |
1371 |
> |
return true; // no compensation needed |
1372 |
> |
} |
1373 |
> |
else if (tc + pc < MAX_ID) { |
1374 |
> |
long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK); |
1375 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
1376 |
> |
addWorker(); |
1377 |
> |
return true; // create replacement |
1378 |
> |
} |
1379 |
> |
} |
1380 |
> |
} |
1381 |
> |
return false; |
1382 |
> |
} |
1383 |
|
|
1384 |
< |
// Constructors |
1384 |
> |
// Submissions |
1385 |
|
|
1386 |
|
/** |
1387 |
< |
* Creates a ForkJoinPool with a pool size equal to the number of |
1388 |
< |
* processors available on the system and using the default |
1389 |
< |
* ForkJoinWorkerThreadFactory, |
1390 |
< |
* @throws SecurityException if a security manager exists and |
334 |
< |
* the caller is not permitted to modify threads |
335 |
< |
* because it does not hold {@link |
336 |
< |
* java.lang.RuntimePermission}<code>("modifyThread")</code>, |
1387 |
> |
* Unless shutting down, adds the given task to a submission queue |
1388 |
> |
* at submitter's current queue index. If no queue exists at the |
1389 |
> |
* index, one is created unless pool lock is busy. If the queue |
1390 |
> |
* and/or lock are busy, another index is randomly chosen. |
1391 |
|
*/ |
1392 |
< |
public ForkJoinPool() { |
1393 |
< |
this(Runtime.getRuntime().availableProcessors(), |
1394 |
< |
defaultForkJoinWorkerThreadFactory); |
1392 |
> |
private void doSubmit(ForkJoinTask<?> task) { |
1393 |
> |
if (task == null) |
1394 |
> |
throw new NullPointerException(); |
1395 |
> |
Submitter s = submitters.get(); |
1396 |
> |
for (int r = s.seed;;) { |
1397 |
> |
WorkQueue q; int k; |
1398 |
> |
int rs = runState, m = rs & SMASK; |
1399 |
> |
WorkQueue[] ws = workQueues; |
1400 |
> |
if (rs < 0 || ws == null) // shutting down |
1401 |
> |
throw new RejectedExecutionException(); |
1402 |
> |
if (ws.length > m && // k must be at index |
1403 |
> |
((q = ws[k = (r << 1) & m]) != null || |
1404 |
> |
(q = tryAddSharedQueue(k)) != null) && |
1405 |
> |
q.trySharedPush(task)) { |
1406 |
> |
signalWork(); |
1407 |
> |
return; |
1408 |
> |
} |
1409 |
> |
r ^= r << 13; // xorshift seed to new position |
1410 |
> |
r ^= r >>> 17; |
1411 |
> |
if (((s.seed = r ^= r << 5) & m) == 0) |
1412 |
> |
Thread.yield(); // occasionally yield if busy |
1413 |
> |
} |
1414 |
> |
} |
1415 |
> |
|
1416 |
> |
|
1417 |
> |
// Scanning for tasks |
1418 |
> |
|
1419 |
> |
/** |
1420 |
> |
* Scans for and, if found, returns one task, else possibly |
1421 |
> |
* inactivates the worker. This method operates on single reads of |
1422 |
> |
* volatile state and is designed to be re-invoked continuously in |
1423 |
> |
* part because it returns upon detecting inconsistencies, |
1424 |
> |
* contention, or state changes that indicate possible success on |
1425 |
> |
* re-invocation. |
1426 |
> |
* |
1427 |
> |
* The scan searches for tasks across queues, randomly selecting |
1428 |
> |
* the first #queues probes, favoring steals 2:1 over submissions |
1429 |
> |
* (by exploiting even/odd indexing), and then performing a |
1430 |
> |
* circular sweep of all queues. The scan terminates upon either |
1431 |
> |
* finding a non-empty queue, or completing a full sweep. If the |
1432 |
> |
* worker is not inactivated, it takes and returns a task from |
1433 |
> |
* this queue. On failure to find a task, we take one of the |
1434 |
> |
* following actions, after which the caller will retry calling |
1435 |
> |
* this method unless terminated. |
1436 |
> |
* |
1437 |
> |
* * If not a complete sweep, try to release a waiting worker. If |
1438 |
> |
* the scan terminated because the worker is inactivated, then the |
1439 |
> |
* released worker will often be the calling worker, and it can |
1440 |
> |
* succeed obtaining a task on the next call. Or maybe it is |
1441 |
> |
* another worker, but with same net effect. Releasing in other |
1442 |
> |
* cases as well ensures that we have enough workers running. |
1443 |
> |
* |
1444 |
> |
* * If the caller has run a task since the the last empty scan, |
1445 |
> |
* return (to allow rescan) if other workers are not also yet |
1446 |
> |
* enqueued. Field WorkQueue.rescans counts down on each scan to |
1447 |
> |
* ensure eventual inactivation, and occasional calls to |
1448 |
> |
* Thread.yield to help avoid interference with more useful |
1449 |
> |
* activities on the system. |
1450 |
> |
* |
1451 |
> |
* * If pool is terminating, terminate the worker. |
1452 |
> |
* |
1453 |
> |
* * If not already enqueued, try to inactivate and enqueue the |
1454 |
> |
* worker on wait queue. |
1455 |
> |
* |
1456 |
> |
* * If already enqueued and none of the above apply, either park |
1457 |
> |
* awaiting signal, or if this is the most recent waiter and pool |
1458 |
> |
* is quiescent, relay to idleAwaitWork to check for termination |
1459 |
> |
* and possibly shrink pool. |
1460 |
> |
* |
1461 |
> |
* @param w the worker (via its WorkQueue) |
1462 |
> |
* @return a task or null of none found |
1463 |
> |
*/ |
1464 |
> |
private final ForkJoinTask<?> scan(WorkQueue w) { |
1465 |
> |
boolean swept = false; // true after full empty scan |
1466 |
> |
WorkQueue[] ws; // volatile read order matters |
1467 |
> |
int r = w.seed, ec = w.eventCount; // ec is negative if inactive |
1468 |
> |
int rs = runState, m = rs & SMASK; |
1469 |
> |
if ((ws = workQueues) != null && ws.length > m) { |
1470 |
> |
ForkJoinTask<?> task = null; |
1471 |
> |
for (int k = 0, j = -2 - m; ; ++j) { |
1472 |
> |
WorkQueue q; int b; |
1473 |
> |
if (j < 0) { // random probes while j negative |
1474 |
> |
r ^= r << 13; r ^= r >>> 17; k = (r ^= r << 5) | (j & 1); |
1475 |
> |
} // worker (not submit) for odd j |
1476 |
> |
else // cyclic scan when j >= 0 |
1477 |
> |
k += (m >>> 1) | 1; // step by half to reduce bias |
1478 |
> |
|
1479 |
> |
if ((q = ws[k & m]) != null && (b = q.base) - q.top < 0) { |
1480 |
> |
if (ec >= 0) |
1481 |
> |
task = q.pollAt(b); // steal |
1482 |
> |
break; |
1483 |
> |
} |
1484 |
> |
else if (j > m) { |
1485 |
> |
if (rs == runState) // staleness check |
1486 |
> |
swept = true; |
1487 |
> |
break; |
1488 |
> |
} |
1489 |
> |
} |
1490 |
> |
w.seed = r; // save seed for next scan |
1491 |
> |
if (task != null) |
1492 |
> |
return task; |
1493 |
> |
} |
1494 |
> |
|
1495 |
> |
// Decode ctl on empty scan |
1496 |
> |
long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns; |
1497 |
> |
if (!swept) { // try to release a waiter |
1498 |
> |
WorkQueue v; Thread p; |
1499 |
> |
if (e > 0 && a < 0 && ws != null && |
1500 |
> |
(v = ws[((~e << 1) | 1) & m]) != null && |
1501 |
> |
v.eventCount == (e | INT_SIGN) && U.compareAndSwapLong |
1502 |
> |
(this, CTL, c, ((long)(v.nextWait & E_MASK) | |
1503 |
> |
((c + AC_UNIT) & (AC_MASK|TC_MASK))))) { |
1504 |
> |
v.eventCount = (e + E_SEQ) & E_MASK; |
1505 |
> |
if ((p = v.parker) != null) |
1506 |
> |
U.unpark(p); |
1507 |
> |
} |
1508 |
> |
} |
1509 |
> |
else if ((nr = w.rescans) > 0) { // continue rescanning |
1510 |
> |
int ac = a + parallelism; |
1511 |
> |
if ((w.rescans = (ac < nr) ? ac : nr - 1) > 0 && w.seed < 0 && |
1512 |
> |
w.eventCount == ec) |
1513 |
> |
Thread.yield(); // 1 bit randomness for yield call |
1514 |
> |
} |
1515 |
> |
else if (e < 0) // pool is terminating |
1516 |
> |
w.runState = -1; |
1517 |
> |
else if (ec >= 0) { // try to enqueue |
1518 |
> |
long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK)); |
1519 |
> |
w.nextWait = e; |
1520 |
> |
w.eventCount = ec | INT_SIGN; // mark as inactive |
1521 |
> |
if (!U.compareAndSwapLong(this, CTL, c, nc)) |
1522 |
> |
w.eventCount = ec; // back out on CAS failure |
1523 |
> |
else if ((ns = w.nsteals) != 0) { // set rescans if ran task |
1524 |
> |
if (a <= 0) // ... unless too many active |
1525 |
> |
w.rescans = a + parallelism; |
1526 |
> |
w.nsteals = 0; |
1527 |
> |
w.totalSteals += ns; |
1528 |
> |
} |
1529 |
> |
} |
1530 |
> |
else{ // already queued |
1531 |
> |
if (parallelism == -a) |
1532 |
> |
idleAwaitWork(w); // quiescent |
1533 |
> |
if (w.eventCount == ec) { |
1534 |
> |
Thread.interrupted(); // clear status |
1535 |
> |
ForkJoinWorkerThread wt = w.owner; |
1536 |
> |
U.putObject(wt, PARKBLOCKER, this); |
1537 |
> |
w.parker = wt; // emulate LockSupport.park |
1538 |
> |
if (w.eventCount == ec) // recheck |
1539 |
> |
U.park(false, 0L); // block |
1540 |
> |
w.parker = null; |
1541 |
> |
U.putObject(wt, PARKBLOCKER, null); |
1542 |
> |
} |
1543 |
> |
} |
1544 |
> |
return null; |
1545 |
> |
} |
1546 |
> |
|
1547 |
> |
/** |
1548 |
> |
* If inactivating worker w has caused pool to become quiescent, |
1549 |
> |
* checks for pool termination, and, so long as this is not the |
1550 |
> |
* only worker, waits for event for up to SHRINK_RATE nanosecs. |
1551 |
> |
* On timeout, if ctl has not changed, terminates the worker, |
1552 |
> |
* which will in turn wake up another worker to possibly repeat |
1553 |
> |
* this process. |
1554 |
> |
* |
1555 |
> |
* @param w the calling worker |
1556 |
> |
*/ |
1557 |
> |
private void idleAwaitWork(WorkQueue w) { |
1558 |
> |
long c; int nw, ec; |
1559 |
> |
if (!tryTerminate(false) && |
1560 |
> |
(int)((c = ctl) >> AC_SHIFT) + parallelism == 0 && |
1561 |
> |
(ec = w.eventCount) == ((int)c | INT_SIGN) && |
1562 |
> |
(nw = w.nextWait) != 0) { |
1563 |
> |
long nc = ((long)(nw & E_MASK) | // ctl to restore on timeout |
1564 |
> |
((c + AC_UNIT) & AC_MASK) | (c & TC_MASK)); |
1565 |
> |
ForkJoinTask.helpExpungeStaleExceptions(); // help clean |
1566 |
> |
ForkJoinWorkerThread wt = w.owner; |
1567 |
> |
while (ctl == c) { |
1568 |
> |
long startTime = System.nanoTime(); |
1569 |
> |
Thread.interrupted(); // timed variant of version in scan() |
1570 |
> |
U.putObject(wt, PARKBLOCKER, this); |
1571 |
> |
w.parker = wt; |
1572 |
> |
if (ctl == c) |
1573 |
> |
U.park(false, SHRINK_RATE); |
1574 |
> |
w.parker = null; |
1575 |
> |
U.putObject(wt, PARKBLOCKER, null); |
1576 |
> |
if (ctl != c) |
1577 |
> |
break; |
1578 |
> |
if (System.nanoTime() - startTime >= SHRINK_TIMEOUT && |
1579 |
> |
U.compareAndSwapLong(this, CTL, c, nc)) { |
1580 |
> |
w.runState = -1; // shrink |
1581 |
> |
w.eventCount = (ec + E_SEQ) | E_MASK; |
1582 |
> |
break; |
1583 |
> |
} |
1584 |
> |
} |
1585 |
> |
} |
1586 |
|
} |
1587 |
|
|
1588 |
|
/** |
1589 |
< |
* Creates a ForkJoinPool with the indicated parellelism level |
1590 |
< |
* threads, and using the default ForkJoinWorkerThreadFactory, |
1591 |
< |
* @param parallelism the number of worker threads |
1592 |
< |
* @throws IllegalArgumentException if parallelism less than or |
1593 |
< |
* equal to zero |
1594 |
< |
* @throws SecurityException if a security manager exists and |
1595 |
< |
* the caller is not permitted to modify threads |
1596 |
< |
* because it does not hold {@link |
1597 |
< |
* java.lang.RuntimePermission}<code>("modifyThread")</code>, |
1598 |
< |
*/ |
1599 |
< |
public ForkJoinPool(int parallelism) { |
1600 |
< |
this(parallelism, defaultForkJoinWorkerThreadFactory); |
1589 |
> |
* Tries to locate and execute tasks for a stealer of the given |
1590 |
> |
* task, or in turn one of its stealers, Traces currentSteal -> |
1591 |
> |
* currentJoin links looking for a thread working on a descendant |
1592 |
> |
* of the given task and with a non-empty queue to steal back and |
1593 |
> |
* execute tasks from. The first call to this method upon a |
1594 |
> |
* waiting join will often entail scanning/search, (which is OK |
1595 |
> |
* because the joiner has nothing better to do), but this method |
1596 |
> |
* leaves hints in workers to speed up subsequent calls. The |
1597 |
> |
* implementation is very branchy to cope with potential |
1598 |
> |
* inconsistencies or loops encountering chains that are stale, |
1599 |
> |
* unknown, or of length greater than MAX_HELP_DEPTH links. All |
1600 |
> |
* of these cases are dealt with by just retrying by caller. |
1601 |
> |
* |
1602 |
> |
* @param joiner the joining worker |
1603 |
> |
* @param task the task to join |
1604 |
> |
* @return true if found or ran a task (and so is immediately retryable) |
1605 |
> |
*/ |
1606 |
> |
final boolean tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) { |
1607 |
> |
ForkJoinTask<?> subtask; // current target |
1608 |
> |
boolean progress = false; |
1609 |
> |
int depth = 0; // current chain depth |
1610 |
> |
int m = runState & SMASK; |
1611 |
> |
WorkQueue[] ws = workQueues; |
1612 |
> |
|
1613 |
> |
if (ws != null && ws.length > m && (subtask = task).status >= 0) { |
1614 |
> |
outer:for (WorkQueue j = joiner;;) { |
1615 |
> |
// Try to find the stealer of subtask, by first using hint |
1616 |
> |
WorkQueue stealer = null; |
1617 |
> |
WorkQueue v = ws[j.stealHint & m]; |
1618 |
> |
if (v != null && v.currentSteal == subtask) |
1619 |
> |
stealer = v; |
1620 |
> |
else { |
1621 |
> |
for (int i = 1; i <= m; i += 2) { |
1622 |
> |
if ((v = ws[i]) != null && v.currentSteal == subtask) { |
1623 |
> |
stealer = v; |
1624 |
> |
j.stealHint = i; // save hint |
1625 |
> |
break; |
1626 |
> |
} |
1627 |
> |
} |
1628 |
> |
if (stealer == null) |
1629 |
> |
break; |
1630 |
> |
} |
1631 |
> |
|
1632 |
> |
for (WorkQueue q = stealer;;) { // Try to help stealer |
1633 |
> |
ForkJoinTask<?> t; int b; |
1634 |
> |
if (task.status < 0) |
1635 |
> |
break outer; |
1636 |
> |
if ((b = q.base) - q.top < 0) { |
1637 |
> |
progress = true; |
1638 |
> |
if (subtask.status < 0) |
1639 |
> |
break outer; // stale |
1640 |
> |
if ((t = q.pollAt(b)) != null) { |
1641 |
> |
stealer.stealHint = joiner.poolIndex; |
1642 |
> |
joiner.runSubtask(t); |
1643 |
> |
} |
1644 |
> |
} |
1645 |
> |
else { // empty - try to descend to find stealer's stealer |
1646 |
> |
ForkJoinTask<?> next = stealer.currentJoin; |
1647 |
> |
if (++depth == MAX_HELP_DEPTH || subtask.status < 0 || |
1648 |
> |
next == null || next == subtask) |
1649 |
> |
break outer; // max depth, stale, dead-end, cyclic |
1650 |
> |
subtask = next; |
1651 |
> |
j = stealer; |
1652 |
> |
break; |
1653 |
> |
} |
1654 |
> |
} |
1655 |
> |
} |
1656 |
> |
} |
1657 |
> |
return progress; |
1658 |
|
} |
1659 |
|
|
1660 |
|
/** |
1661 |
< |
* Creates a ForkJoinPool with parallelism equal to the number of |
1662 |
< |
* processors available on the system and using the given |
1663 |
< |
* ForkJoinWorkerThreadFactory, |
1664 |
< |
* @param factory the factory for creating new threads |
363 |
< |
* @throws NullPointerException if factory is null |
364 |
< |
* @throws SecurityException if a security manager exists and |
365 |
< |
* the caller is not permitted to modify threads |
366 |
< |
* because it does not hold {@link |
367 |
< |
* java.lang.RuntimePermission}<code>("modifyThread")</code>, |
1661 |
> |
* If task is at base of some steal queue, steals and executes it. |
1662 |
> |
* |
1663 |
> |
* @param joiner the joining worker |
1664 |
> |
* @param task the task |
1665 |
|
*/ |
1666 |
< |
public ForkJoinPool(ForkJoinWorkerThreadFactory factory) { |
1667 |
< |
this(Runtime.getRuntime().availableProcessors(), factory); |
1666 |
> |
final void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) { |
1667 |
> |
WorkQueue[] ws; |
1668 |
> |
int m = runState & SMASK; |
1669 |
> |
if ((ws = workQueues) != null && ws.length > m) { |
1670 |
> |
for (int j = 1; j <= m && task.status >= 0; j += 2) { |
1671 |
> |
WorkQueue q = ws[j]; |
1672 |
> |
if (q != null && q.pollFor(task)) { |
1673 |
> |
joiner.runSubtask(task); |
1674 |
> |
break; |
1675 |
> |
} |
1676 |
> |
} |
1677 |
> |
} |
1678 |
|
} |
1679 |
|
|
1680 |
|
/** |
1681 |
< |
* Creates a ForkJoinPool with the given parallelism and factory. |
1682 |
< |
* |
1683 |
< |
* @param parallelism the targeted number of worker threads |
1684 |
< |
* @param factory the factory for creating new threads |
1685 |
< |
* @throws IllegalArgumentException if parallelism less than or |
1686 |
< |
* equal to zero, or greater than implementation limit. |
1687 |
< |
* @throws NullPointerException if factory is null |
1688 |
< |
* @throws SecurityException if a security manager exists and |
1689 |
< |
* the caller is not permitted to modify threads |
1690 |
< |
* because it does not hold {@link |
1691 |
< |
* java.lang.RuntimePermission}<code>("modifyThread")</code>, |
1692 |
< |
*/ |
1693 |
< |
public ForkJoinPool(int parallelism, ForkJoinWorkerThreadFactory factory) { |
1694 |
< |
if (parallelism <= 0 || parallelism > MAX_THREADS) |
1695 |
< |
throw new IllegalArgumentException(); |
1696 |
< |
if (factory == null) |
1697 |
< |
throw new NullPointerException(); |
1698 |
< |
checkPermission(); |
1699 |
< |
this.factory = factory; |
1700 |
< |
this.parallelism = parallelism; |
1701 |
< |
this.maxPoolSize = MAX_THREADS; |
1702 |
< |
this.maintainsParallelism = true; |
1703 |
< |
this.poolNumber = poolNumberGenerator.incrementAndGet(); |
1704 |
< |
this.workerLock = new ReentrantLock(); |
1705 |
< |
this.termination = workerLock.newCondition(); |
1706 |
< |
this.stealCount = new AtomicLong(); |
400 |
< |
this.submissionQueue = new LinkedTransferQueue<ForkJoinTask<?>>(); |
401 |
< |
// worker array and workers are lazily constructed |
1681 |
> |
* Returns a non-empty steal queue, if one is found during a random, |
1682 |
> |
* then cyclic scan, else null. This method must be retried by |
1683 |
> |
* caller if, by the time it tries to use the queue, it is empty. |
1684 |
> |
*/ |
1685 |
> |
private WorkQueue findNonEmptyStealQueue(WorkQueue w) { |
1686 |
> |
int r = w.seed; // Same idea as scan(), but ignoring submissions |
1687 |
> |
for (WorkQueue[] ws;;) { |
1688 |
> |
int m = runState & SMASK; |
1689 |
> |
if ((ws = workQueues) == null) |
1690 |
> |
return null; |
1691 |
> |
if (ws.length > m) { |
1692 |
> |
WorkQueue q; |
1693 |
> |
for (int n = m << 2, k = r, j = -n;;) { |
1694 |
> |
r ^= r << 13; r ^= r >>> 17; r ^= r << 5; |
1695 |
> |
if ((q = ws[(k | 1) & m]) != null && q.base - q.top < 0) { |
1696 |
> |
w.seed = r; |
1697 |
> |
return q; |
1698 |
> |
} |
1699 |
> |
else if (j > n) |
1700 |
> |
return null; |
1701 |
> |
else |
1702 |
> |
k = (j++ < 0) ? r : k + ((m >>> 1) | 1); |
1703 |
> |
|
1704 |
> |
} |
1705 |
> |
} |
1706 |
> |
} |
1707 |
|
} |
1708 |
|
|
1709 |
|
/** |
1710 |
< |
* Create new worker using factory. |
1711 |
< |
* @param index the index to assign worker |
1712 |
< |
* @return new worker, or null of factory failed |
1713 |
< |
*/ |
1714 |
< |
private ForkJoinWorkerThread createWorker(int index) { |
1715 |
< |
Thread.UncaughtExceptionHandler h = ueh; |
1716 |
< |
ForkJoinWorkerThread w = factory.newThread(this); |
1717 |
< |
if (w != null) { |
1718 |
< |
w.poolIndex = index; |
1719 |
< |
w.setDaemon(true); |
1720 |
< |
w.setAsyncMode(locallyFifo); |
1721 |
< |
w.setName("ForkJoinPool-" + poolNumber + "-worker-" + index); |
1722 |
< |
if (h != null) |
1723 |
< |
w.setUncaughtExceptionHandler(h); |
1710 |
> |
* Runs tasks until {@code isQuiescent()}. We piggyback on |
1711 |
> |
* active count ctl maintenance, but rather than blocking |
1712 |
> |
* when tasks cannot be found, we rescan until all others cannot |
1713 |
> |
* find tasks either. |
1714 |
> |
*/ |
1715 |
> |
final void helpQuiescePool(WorkQueue w) { |
1716 |
> |
for (boolean active = true;;) { |
1717 |
> |
w.runLocalTasks(); // exhaust local queue |
1718 |
> |
WorkQueue q = findNonEmptyStealQueue(w); |
1719 |
> |
if (q != null) { |
1720 |
> |
ForkJoinTask<?> t; |
1721 |
> |
if (!active) { // re-establish active count |
1722 |
> |
long c; |
1723 |
> |
active = true; |
1724 |
> |
do {} while (!U.compareAndSwapLong |
1725 |
> |
(this, CTL, c = ctl, c + AC_UNIT)); |
1726 |
> |
} |
1727 |
> |
if ((t = q.poll()) != null) |
1728 |
> |
w.runSubtask(t); |
1729 |
> |
} |
1730 |
> |
else { |
1731 |
> |
long c; |
1732 |
> |
if (active) { // decrement active count without queuing |
1733 |
> |
active = false; |
1734 |
> |
do {} while (!U.compareAndSwapLong |
1735 |
> |
(this, CTL, c = ctl, c -= AC_UNIT)); |
1736 |
> |
} |
1737 |
> |
else |
1738 |
> |
c = ctl; // re-increment on exit |
1739 |
> |
if ((int)(c >> AC_SHIFT) + parallelism == 0) { |
1740 |
> |
do {} while (!U.compareAndSwapLong |
1741 |
> |
(this, CTL, c = ctl, c + AC_UNIT)); |
1742 |
> |
break; |
1743 |
> |
} |
1744 |
> |
} |
1745 |
|
} |
420 |
– |
return w; |
1746 |
|
} |
1747 |
|
|
1748 |
|
/** |
1749 |
< |
* Return a good size for worker array given pool size. |
1750 |
< |
* Currently requires size to be a power of two. |
1749 |
> |
* Gets and removes a local or stolen task for the given worker. |
1750 |
> |
* |
1751 |
> |
* @return a task, if available |
1752 |
|
*/ |
1753 |
< |
private static int arraySizeFor(int ps) { |
1754 |
< |
return ps <= 1? 1 : (1 << (32 - Integer.numberOfLeadingZeros(ps-1))); |
1753 |
> |
final ForkJoinTask<?> nextTaskFor(WorkQueue w) { |
1754 |
> |
for (ForkJoinTask<?> t;;) { |
1755 |
> |
WorkQueue q; |
1756 |
> |
if ((t = w.nextLocalTask()) != null) |
1757 |
> |
return t; |
1758 |
> |
if ((q = findNonEmptyStealQueue(w)) == null) |
1759 |
> |
return null; |
1760 |
> |
if ((t = q.poll()) != null) |
1761 |
> |
return t; |
1762 |
> |
} |
1763 |
|
} |
1764 |
|
|
1765 |
|
/** |
1766 |
< |
* Create or resize array if necessary to hold newLength. |
1767 |
< |
* Call only under exlusion or lock |
1768 |
< |
* @return the array |
1766 |
> |
* Returns the approximate (non-atomic) number of idle threads per |
1767 |
> |
* active thread to offset steal queue size for method |
1768 |
> |
* ForkJoinTask.getSurplusQueuedTaskCount(). |
1769 |
|
*/ |
1770 |
< |
private ForkJoinWorkerThread[] ensureWorkerArrayCapacity(int newLength) { |
1771 |
< |
ForkJoinWorkerThread[] ws = workers; |
1772 |
< |
if (ws == null) |
1773 |
< |
return workers = new ForkJoinWorkerThread[arraySizeFor(newLength)]; |
1774 |
< |
else if (newLength > ws.length) |
1775 |
< |
return workers = Arrays.copyOf(ws, arraySizeFor(newLength)); |
1776 |
< |
else |
1777 |
< |
return ws; |
1770 |
> |
final int idlePerActive() { |
1771 |
> |
// Approximate at powers of two for small values, saturate past 4 |
1772 |
> |
int p = parallelism; |
1773 |
> |
int a = p + (int)(ctl >> AC_SHIFT); |
1774 |
> |
return (a > (p >>>= 1) ? 0 : |
1775 |
> |
a > (p >>>= 1) ? 1 : |
1776 |
> |
a > (p >>>= 1) ? 2 : |
1777 |
> |
a > (p >>>= 1) ? 4 : |
1778 |
> |
8); |
1779 |
|
} |
1780 |
|
|
1781 |
+ |
// Termination |
1782 |
+ |
|
1783 |
|
/** |
1784 |
< |
* Try to shrink workers into smaller array after one or more terminate |
1784 |
> |
* Sets SHUTDOWN bit of runState under lock |
1785 |
|
*/ |
1786 |
< |
private void tryShrinkWorkerArray() { |
1787 |
< |
ForkJoinWorkerThread[] ws = workers; |
1788 |
< |
if (ws != null) { |
1789 |
< |
int len = ws.length; |
1790 |
< |
int last = len - 1; |
1791 |
< |
while (last >= 0 && ws[last] == null) |
455 |
< |
--last; |
456 |
< |
int newLength = arraySizeFor(last+1); |
457 |
< |
if (newLength < len) |
458 |
< |
workers = Arrays.copyOf(ws, newLength); |
1786 |
> |
private void enableShutdown() { |
1787 |
> |
ReentrantLock lock = this.lock; |
1788 |
> |
if (runState >= 0) { |
1789 |
> |
lock.lock(); // don't need try/finally |
1790 |
> |
runState |= SHUTDOWN; |
1791 |
> |
lock.unlock(); |
1792 |
|
} |
1793 |
|
} |
1794 |
|
|
1795 |
|
/** |
1796 |
< |
* Initialize workers if necessary |
1797 |
< |
*/ |
1798 |
< |
final void ensureWorkerInitialization() { |
1799 |
< |
ForkJoinWorkerThread[] ws = workers; |
1800 |
< |
if (ws == null) { |
1801 |
< |
final ReentrantLock lock = this.workerLock; |
1802 |
< |
lock.lock(); |
1803 |
< |
try { |
1804 |
< |
ws = workers; |
1805 |
< |
if (ws == null) { |
1806 |
< |
int ps = parallelism; |
1807 |
< |
ws = ensureWorkerArrayCapacity(ps); |
1808 |
< |
for (int i = 0; i < ps; ++i) { |
1809 |
< |
ForkJoinWorkerThread w = createWorker(i); |
1810 |
< |
if (w != null) { |
1811 |
< |
ws[i] = w; |
1812 |
< |
w.start(); |
1813 |
< |
updateWorkerCount(1); |
1814 |
< |
} |
1796 |
> |
* Possibly initiates and/or completes termination. Upon |
1797 |
> |
* termination, cancels all queued tasks and then |
1798 |
> |
* |
1799 |
> |
* @param now if true, unconditionally terminate, else only |
1800 |
> |
* if no work and no active workers |
1801 |
> |
* @return true if now terminating or terminated |
1802 |
> |
*/ |
1803 |
> |
private boolean tryTerminate(boolean now) { |
1804 |
> |
for (long c;;) { |
1805 |
> |
if (((c = ctl) & STOP_BIT) != 0) { // already terminating |
1806 |
> |
if ((short)(c >>> TC_SHIFT) == -parallelism) { |
1807 |
> |
ReentrantLock lock = this.lock; // signal when no workers |
1808 |
> |
lock.lock(); // don't need try/finally |
1809 |
> |
termination.signalAll(); // signal when 0 workers |
1810 |
> |
lock.unlock(); |
1811 |
> |
} |
1812 |
> |
return true; |
1813 |
> |
} |
1814 |
> |
if (!now) { |
1815 |
> |
if ((int)(c >> AC_SHIFT) != -parallelism || runState >= 0 || |
1816 |
> |
hasQueuedSubmissions()) |
1817 |
> |
return false; |
1818 |
> |
// Check for unqueued inactive workers. One pass suffices. |
1819 |
> |
WorkQueue[] ws = workQueues; WorkQueue w; |
1820 |
> |
if (ws != null) { |
1821 |
> |
int n = ws.length; |
1822 |
> |
for (int i = 1; i < n; i += 2) { |
1823 |
> |
if ((w = ws[i]) != null && w.eventCount >= 0) |
1824 |
> |
return false; |
1825 |
|
} |
1826 |
|
} |
484 |
– |
} finally { |
485 |
– |
lock.unlock(); |
1827 |
|
} |
1828 |
+ |
if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) |
1829 |
+ |
startTerminating(); |
1830 |
|
} |
1831 |
|
} |
1832 |
|
|
1833 |
|
/** |
1834 |
< |
* Worker creation and startup for threads added via setParallelism. |
1834 |
> |
* Initiates termination: Runs three passes through workQueues: |
1835 |
> |
* (0) Setting termination status, followed by wakeups of queued |
1836 |
> |
* workers; (1) cancelling all tasks; (2) interrupting lagging |
1837 |
> |
* threads (likely in external tasks, but possibly also blocked in |
1838 |
> |
* joins). Each pass repeats previous steps because of potential |
1839 |
> |
* lagging thread creation. |
1840 |
|
*/ |
1841 |
< |
private void createAndStartAddedWorkers() { |
1842 |
< |
resumeAllSpares(); // Allow spares to convert to nonspare |
1843 |
< |
int ps = parallelism; |
1844 |
< |
ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(ps); |
1845 |
< |
int len = ws.length; |
1846 |
< |
// Sweep through slots, to keep lowest indices most populated |
1847 |
< |
int k = 0; |
1848 |
< |
while (k < len) { |
1849 |
< |
if (ws[k] != null) { |
1850 |
< |
++k; |
1851 |
< |
continue; |
1852 |
< |
} |
1853 |
< |
int s = workerCounts; |
1854 |
< |
int tc = totalCountOf(s); |
1855 |
< |
int rc = runningCountOf(s); |
1856 |
< |
if (rc >= ps || tc >= ps) |
1857 |
< |
break; |
1858 |
< |
if (casWorkerCounts (s, workerCountsFor(tc+1, rc+1))) { |
1859 |
< |
ForkJoinWorkerThread w = createWorker(k); |
1860 |
< |
if (w != null) { |
513 |
< |
ws[k++] = w; |
514 |
< |
w.start(); |
1841 |
> |
private void startTerminating() { |
1842 |
> |
for (int pass = 0; pass < 3; ++pass) { |
1843 |
> |
WorkQueue[] ws = workQueues; |
1844 |
> |
if (ws != null) { |
1845 |
> |
WorkQueue w; Thread wt; |
1846 |
> |
int n = ws.length; |
1847 |
> |
for (int j = 0; j < n; ++j) { |
1848 |
> |
if ((w = ws[j]) != null) { |
1849 |
> |
w.runState = -1; |
1850 |
> |
if (pass > 0) { |
1851 |
> |
w.cancelAll(); |
1852 |
> |
if (pass > 1 && (wt = w.owner) != null && |
1853 |
> |
!wt.isInterrupted()) { |
1854 |
> |
try { |
1855 |
> |
wt.interrupt(); |
1856 |
> |
} catch (SecurityException ignore) { |
1857 |
> |
} |
1858 |
> |
} |
1859 |
> |
} |
1860 |
> |
} |
1861 |
|
} |
1862 |
< |
else { |
1863 |
< |
updateWorkerCount(-1); // back out on failed creation |
1864 |
< |
break; |
1862 |
> |
// Wake up workers parked on event queue |
1863 |
> |
int i, e; long c; Thread p; |
1864 |
> |
while ((i = ((~(e = (int)(c = ctl)) << 1) | 1) & SMASK) < n && |
1865 |
> |
(w = ws[i]) != null && |
1866 |
> |
w.eventCount == (e | INT_SIGN)) { |
1867 |
> |
long nc = ((long)(w.nextWait & E_MASK) | |
1868 |
> |
((c + AC_UNIT) & AC_MASK) | |
1869 |
> |
(c & (TC_MASK|STOP_BIT))); |
1870 |
> |
if (U.compareAndSwapLong(this, CTL, c, nc)) { |
1871 |
> |
w.eventCount = (e + E_SEQ) & E_MASK; |
1872 |
> |
if ((p = w.parker) != null) |
1873 |
> |
U.unpark(p); |
1874 |
> |
} |
1875 |
|
} |
1876 |
|
} |
1877 |
|
} |
1878 |
|
} |
1879 |
|
|
1880 |
< |
// Execution methods |
1880 |
> |
// Exported methods |
1881 |
> |
|
1882 |
> |
// Constructors |
1883 |
> |
|
1884 |
> |
/** |
1885 |
> |
* Creates a {@code ForkJoinPool} with parallelism equal to {@link |
1886 |
> |
* java.lang.Runtime#availableProcessors}, using the {@linkplain |
1887 |
> |
* #defaultForkJoinWorkerThreadFactory default thread factory}, |
1888 |
> |
* no UncaughtExceptionHandler, and non-async LIFO processing mode. |
1889 |
> |
* |
1890 |
> |
* @throws SecurityException if a security manager exists and |
1891 |
> |
* the caller is not permitted to modify threads |
1892 |
> |
* because it does not hold {@link |
1893 |
> |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
1894 |
> |
*/ |
1895 |
> |
public ForkJoinPool() { |
1896 |
> |
this(Runtime.getRuntime().availableProcessors(), |
1897 |
> |
defaultForkJoinWorkerThreadFactory, null, false); |
1898 |
> |
} |
1899 |
|
|
1900 |
|
/** |
1901 |
< |
* Common code for execute, invoke and submit |
1901 |
> |
* Creates a {@code ForkJoinPool} with the indicated parallelism |
1902 |
> |
* level, the {@linkplain |
1903 |
> |
* #defaultForkJoinWorkerThreadFactory default thread factory}, |
1904 |
> |
* no UncaughtExceptionHandler, and non-async LIFO processing mode. |
1905 |
> |
* |
1906 |
> |
* @param parallelism the parallelism level |
1907 |
> |
* @throws IllegalArgumentException if parallelism less than or |
1908 |
> |
* equal to zero, or greater than implementation limit |
1909 |
> |
* @throws SecurityException if a security manager exists and |
1910 |
> |
* the caller is not permitted to modify threads |
1911 |
> |
* because it does not hold {@link |
1912 |
> |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
1913 |
|
*/ |
1914 |
< |
private <T> void doSubmit(ForkJoinTask<T> task) { |
1915 |
< |
if (isShutdown()) |
531 |
< |
throw new RejectedExecutionException(); |
532 |
< |
if (workers == null) |
533 |
< |
ensureWorkerInitialization(); |
534 |
< |
submissionQueue.offer(task); |
535 |
< |
signalIdleWorkers(); |
1914 |
> |
public ForkJoinPool(int parallelism) { |
1915 |
> |
this(parallelism, defaultForkJoinWorkerThreadFactory, null, false); |
1916 |
|
} |
1917 |
|
|
1918 |
|
/** |
1919 |
< |
* Performs the given task; returning its result upon completion |
1919 |
> |
* Creates a {@code ForkJoinPool} with the given parameters. |
1920 |
> |
* |
1921 |
> |
* @param parallelism the parallelism level. For default value, |
1922 |
> |
* use {@link java.lang.Runtime#availableProcessors}. |
1923 |
> |
* @param factory the factory for creating new threads. For default value, |
1924 |
> |
* use {@link #defaultForkJoinWorkerThreadFactory}. |
1925 |
> |
* @param handler the handler for internal worker threads that |
1926 |
> |
* terminate due to unrecoverable errors encountered while executing |
1927 |
> |
* tasks. For default value, use {@code null}. |
1928 |
> |
* @param asyncMode if true, |
1929 |
> |
* establishes local first-in-first-out scheduling mode for forked |
1930 |
> |
* tasks that are never joined. This mode may be more appropriate |
1931 |
> |
* than default locally stack-based mode in applications in which |
1932 |
> |
* worker threads only process event-style asynchronous tasks. |
1933 |
> |
* For default value, use {@code false}. |
1934 |
> |
* @throws IllegalArgumentException if parallelism less than or |
1935 |
> |
* equal to zero, or greater than implementation limit |
1936 |
> |
* @throws NullPointerException if the factory is null |
1937 |
> |
* @throws SecurityException if a security manager exists and |
1938 |
> |
* the caller is not permitted to modify threads |
1939 |
> |
* because it does not hold {@link |
1940 |
> |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
1941 |
> |
*/ |
1942 |
> |
public ForkJoinPool(int parallelism, |
1943 |
> |
ForkJoinWorkerThreadFactory factory, |
1944 |
> |
Thread.UncaughtExceptionHandler handler, |
1945 |
> |
boolean asyncMode) { |
1946 |
> |
checkPermission(); |
1947 |
> |
if (factory == null) |
1948 |
> |
throw new NullPointerException(); |
1949 |
> |
if (parallelism <= 0 || parallelism > MAX_ID) |
1950 |
> |
throw new IllegalArgumentException(); |
1951 |
> |
this.parallelism = parallelism; |
1952 |
> |
this.factory = factory; |
1953 |
> |
this.ueh = handler; |
1954 |
> |
this.localMode = asyncMode ? FIFO_QUEUE : LIFO_QUEUE; |
1955 |
> |
this.nextPoolIndex = 1; |
1956 |
> |
long np = (long)(-parallelism); // offset ctl counts |
1957 |
> |
this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK); |
1958 |
> |
// initialize workQueues array with room for 2*parallelism if possible |
1959 |
> |
int n = parallelism << 1; |
1960 |
> |
if (n >= MAX_ID) |
1961 |
> |
n = MAX_ID; |
1962 |
> |
else { // See Hackers Delight, sec 3.2, where n < (1 << 16) |
1963 |
> |
n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; |
1964 |
> |
} |
1965 |
> |
this.workQueues = new WorkQueue[(n + 1) << 1]; |
1966 |
> |
ReentrantLock lck = this.lock = new ReentrantLock(); |
1967 |
> |
this.termination = lck.newCondition(); |
1968 |
> |
this.stealCount = new AtomicLong(); |
1969 |
> |
this.nextWorkerNumber = new AtomicInteger(); |
1970 |
> |
StringBuilder sb = new StringBuilder("ForkJoinPool-"); |
1971 |
> |
sb.append(poolNumberGenerator.incrementAndGet()); |
1972 |
> |
sb.append("-worker-"); |
1973 |
> |
this.workerNamePrefix = sb.toString(); |
1974 |
> |
// Create initial submission queue |
1975 |
> |
WorkQueue sq = tryAddSharedQueue(0); |
1976 |
> |
if (sq != null) |
1977 |
> |
sq.growArray(false); |
1978 |
> |
} |
1979 |
> |
|
1980 |
> |
// Execution methods |
1981 |
> |
|
1982 |
> |
/** |
1983 |
> |
* Performs the given task, returning its result upon completion. |
1984 |
> |
* If the computation encounters an unchecked Exception or Error, |
1985 |
> |
* it is rethrown as the outcome of this invocation. Rethrown |
1986 |
> |
* exceptions behave in the same way as regular exceptions, but, |
1987 |
> |
* when possible, contain stack traces (as displayed for example |
1988 |
> |
* using {@code ex.printStackTrace()}) of both the current thread |
1989 |
> |
* as well as the thread actually encountering the exception; |
1990 |
> |
* minimally only the latter. |
1991 |
> |
* |
1992 |
|
* @param task the task |
1993 |
|
* @return the task's result |
1994 |
< |
* @throws NullPointerException if task is null |
1995 |
< |
* @throws RejectedExecutionException if pool is shut down |
1994 |
> |
* @throws NullPointerException if the task is null |
1995 |
> |
* @throws RejectedExecutionException if the task cannot be |
1996 |
> |
* scheduled for execution |
1997 |
|
*/ |
1998 |
|
public <T> T invoke(ForkJoinTask<T> task) { |
1999 |
|
doSubmit(task); |
2002 |
|
|
2003 |
|
/** |
2004 |
|
* Arranges for (asynchronous) execution of the given task. |
2005 |
+ |
* |
2006 |
|
* @param task the task |
2007 |
< |
* @throws NullPointerException if task is null |
2008 |
< |
* @throws RejectedExecutionException if pool is shut down |
2007 |
> |
* @throws NullPointerException if the task is null |
2008 |
> |
* @throws RejectedExecutionException if the task cannot be |
2009 |
> |
* scheduled for execution |
2010 |
|
*/ |
2011 |
< |
public <T> void execute(ForkJoinTask<T> task) { |
2011 |
> |
public void execute(ForkJoinTask<?> task) { |
2012 |
|
doSubmit(task); |
2013 |
|
} |
2014 |
|
|
2015 |
|
// AbstractExecutorService methods |
2016 |
|
|
2017 |
+ |
/** |
2018 |
+ |
* @throws NullPointerException if the task is null |
2019 |
+ |
* @throws RejectedExecutionException if the task cannot be |
2020 |
+ |
* scheduled for execution |
2021 |
+ |
*/ |
2022 |
|
public void execute(Runnable task) { |
2023 |
< |
doSubmit(new AdaptedRunnable<Void>(task, null)); |
2023 |
> |
if (task == null) |
2024 |
> |
throw new NullPointerException(); |
2025 |
> |
ForkJoinTask<?> job; |
2026 |
> |
if (task instanceof ForkJoinTask<?>) // avoid re-wrap |
2027 |
> |
job = (ForkJoinTask<?>) task; |
2028 |
> |
else |
2029 |
> |
job = ForkJoinTask.adapt(task, null); |
2030 |
> |
doSubmit(job); |
2031 |
|
} |
2032 |
|
|
2033 |
+ |
/** |
2034 |
+ |
* Submits a ForkJoinTask for execution. |
2035 |
+ |
* |
2036 |
+ |
* @param task the task to submit |
2037 |
+ |
* @return the task |
2038 |
+ |
* @throws NullPointerException if the task is null |
2039 |
+ |
* @throws RejectedExecutionException if the task cannot be |
2040 |
+ |
* scheduled for execution |
2041 |
+ |
*/ |
2042 |
+ |
public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) { |
2043 |
+ |
doSubmit(task); |
2044 |
+ |
return task; |
2045 |
+ |
} |
2046 |
+ |
|
2047 |
+ |
/** |
2048 |
+ |
* @throws NullPointerException if the task is null |
2049 |
+ |
* @throws RejectedExecutionException if the task cannot be |
2050 |
+ |
* scheduled for execution |
2051 |
+ |
*/ |
2052 |
|
public <T> ForkJoinTask<T> submit(Callable<T> task) { |
2053 |
< |
ForkJoinTask<T> job = new AdaptedCallable<T>(task); |
2053 |
> |
if (task == null) |
2054 |
> |
throw new NullPointerException(); |
2055 |
> |
ForkJoinTask<T> job = ForkJoinTask.adapt(task); |
2056 |
|
doSubmit(job); |
2057 |
|
return job; |
2058 |
|
} |
2059 |
|
|
2060 |
+ |
/** |
2061 |
+ |
* @throws NullPointerException if the task is null |
2062 |
+ |
* @throws RejectedExecutionException if the task cannot be |
2063 |
+ |
* scheduled for execution |
2064 |
+ |
*/ |
2065 |
|
public <T> ForkJoinTask<T> submit(Runnable task, T result) { |
2066 |
< |
ForkJoinTask<T> job = new AdaptedRunnable<T>(task, result); |
2066 |
> |
if (task == null) |
2067 |
> |
throw new NullPointerException(); |
2068 |
> |
ForkJoinTask<T> job = ForkJoinTask.adapt(task, result); |
2069 |
|
doSubmit(job); |
2070 |
|
return job; |
2071 |
|
} |
2072 |
|
|
2073 |
+ |
/** |
2074 |
+ |
* @throws NullPointerException if the task is null |
2075 |
+ |
* @throws RejectedExecutionException if the task cannot be |
2076 |
+ |
* scheduled for execution |
2077 |
+ |
*/ |
2078 |
|
public ForkJoinTask<?> submit(Runnable task) { |
2079 |
< |
ForkJoinTask<Void> job = new AdaptedRunnable<Void>(task, null); |
2079 |
> |
if (task == null) |
2080 |
> |
throw new NullPointerException(); |
2081 |
> |
ForkJoinTask<?> job; |
2082 |
> |
if (task instanceof ForkJoinTask<?>) // avoid re-wrap |
2083 |
> |
job = (ForkJoinTask<?>) task; |
2084 |
> |
else |
2085 |
> |
job = ForkJoinTask.adapt(task, null); |
2086 |
|
doSubmit(job); |
2087 |
|
return job; |
2088 |
|
} |
2089 |
|
|
2090 |
|
/** |
2091 |
< |
* Adaptor for Runnables. This implements RunnableFuture |
2092 |
< |
* to be compliant with AbstractExecutorService constraints |
2091 |
> |
* @throws NullPointerException {@inheritDoc} |
2092 |
> |
* @throws RejectedExecutionException {@inheritDoc} |
2093 |
|
*/ |
588 |
– |
static final class AdaptedRunnable<T> extends ForkJoinTask<T> |
589 |
– |
implements RunnableFuture<T> { |
590 |
– |
final Runnable runnable; |
591 |
– |
final T resultOnCompletion; |
592 |
– |
T result; |
593 |
– |
AdaptedRunnable(Runnable runnable, T result) { |
594 |
– |
if (runnable == null) throw new NullPointerException(); |
595 |
– |
this.runnable = runnable; |
596 |
– |
this.resultOnCompletion = result; |
597 |
– |
} |
598 |
– |
public T getRawResult() { return result; } |
599 |
– |
public void setRawResult(T v) { result = v; } |
600 |
– |
public boolean exec() { |
601 |
– |
runnable.run(); |
602 |
– |
result = resultOnCompletion; |
603 |
– |
return true; |
604 |
– |
} |
605 |
– |
public void run() { invoke(); } |
606 |
– |
} |
607 |
– |
|
608 |
– |
/** |
609 |
– |
* Adaptor for Callables |
610 |
– |
*/ |
611 |
– |
static final class AdaptedCallable<T> extends ForkJoinTask<T> |
612 |
– |
implements RunnableFuture<T> { |
613 |
– |
final Callable<T> callable; |
614 |
– |
T result; |
615 |
– |
AdaptedCallable(Callable<T> callable) { |
616 |
– |
if (callable == null) throw new NullPointerException(); |
617 |
– |
this.callable = callable; |
618 |
– |
} |
619 |
– |
public T getRawResult() { return result; } |
620 |
– |
public void setRawResult(T v) { result = v; } |
621 |
– |
public boolean exec() { |
622 |
– |
try { |
623 |
– |
result = callable.call(); |
624 |
– |
return true; |
625 |
– |
} catch (Error err) { |
626 |
– |
throw err; |
627 |
– |
} catch (RuntimeException rex) { |
628 |
– |
throw rex; |
629 |
– |
} catch (Exception ex) { |
630 |
– |
throw new RuntimeException(ex); |
631 |
– |
} |
632 |
– |
} |
633 |
– |
public void run() { invoke(); } |
634 |
– |
} |
635 |
– |
|
2094 |
|
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) { |
2095 |
< |
ArrayList<ForkJoinTask<T>> ts = |
2095 |
> |
ArrayList<ForkJoinTask<T>> forkJoinTasks = |
2096 |
|
new ArrayList<ForkJoinTask<T>>(tasks.size()); |
2097 |
< |
for (Callable<T> c : tasks) |
2098 |
< |
ts.add(new AdaptedCallable<T>(c)); |
2099 |
< |
invoke(new InvokeAll<T>(ts)); |
2100 |
< |
return (List<Future<T>>)(List)ts; |
2097 |
> |
for (Callable<T> task : tasks) |
2098 |
> |
forkJoinTasks.add(ForkJoinTask.adapt(task)); |
2099 |
> |
invoke(new InvokeAll<T>(forkJoinTasks)); |
2100 |
> |
|
2101 |
> |
@SuppressWarnings({"unchecked", "rawtypes"}) |
2102 |
> |
List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks; |
2103 |
> |
return futures; |
2104 |
|
} |
2105 |
|
|
2106 |
|
static final class InvokeAll<T> extends RecursiveAction { |
2107 |
|
final ArrayList<ForkJoinTask<T>> tasks; |
2108 |
|
InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; } |
2109 |
|
public void compute() { |
2110 |
< |
try { invokeAll(tasks); } catch(Exception ignore) {} |
2110 |
> |
try { invokeAll(tasks); } |
2111 |
> |
catch (Exception ignore) {} |
2112 |
|
} |
2113 |
+ |
private static final long serialVersionUID = -7914297376763021607L; |
2114 |
|
} |
2115 |
|
|
653 |
– |
// Configuration and status settings and queries |
654 |
– |
|
2116 |
|
/** |
2117 |
< |
* Returns the factory used for constructing new workers |
2117 |
> |
* Returns the factory used for constructing new workers. |
2118 |
|
* |
2119 |
|
* @return the factory used for constructing new workers |
2120 |
|
*/ |
2125 |
|
/** |
2126 |
|
* Returns the handler for internal worker threads that terminate |
2127 |
|
* due to unrecoverable errors encountered while executing tasks. |
667 |
– |
* @return the handler, or null if none |
668 |
– |
*/ |
669 |
– |
public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() { |
670 |
– |
Thread.UncaughtExceptionHandler h; |
671 |
– |
final ReentrantLock lock = this.workerLock; |
672 |
– |
lock.lock(); |
673 |
– |
try { |
674 |
– |
h = ueh; |
675 |
– |
} finally { |
676 |
– |
lock.unlock(); |
677 |
– |
} |
678 |
– |
return h; |
679 |
– |
} |
680 |
– |
|
681 |
– |
/** |
682 |
– |
* Sets the handler for internal worker threads that terminate due |
683 |
– |
* to unrecoverable errors encountered while executing tasks. |
684 |
– |
* Unless set, the current default or ThreadGroup handler is used |
685 |
– |
* as handler. |
2128 |
|
* |
2129 |
< |
* @param h the new handler |
688 |
< |
* @return the old handler, or null if none |
689 |
< |
* @throws SecurityException if a security manager exists and |
690 |
< |
* the caller is not permitted to modify threads |
691 |
< |
* because it does not hold {@link |
692 |
< |
* java.lang.RuntimePermission}<code>("modifyThread")</code>, |
2129 |
> |
* @return the handler, or {@code null} if none |
2130 |
|
*/ |
2131 |
< |
public Thread.UncaughtExceptionHandler |
2132 |
< |
setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h) { |
696 |
< |
checkPermission(); |
697 |
< |
Thread.UncaughtExceptionHandler old = null; |
698 |
< |
final ReentrantLock lock = this.workerLock; |
699 |
< |
lock.lock(); |
700 |
< |
try { |
701 |
< |
old = ueh; |
702 |
< |
ueh = h; |
703 |
< |
ForkJoinWorkerThread[] ws = workers; |
704 |
< |
if (ws != null) { |
705 |
< |
for (int i = 0; i < ws.length; ++i) { |
706 |
< |
ForkJoinWorkerThread w = ws[i]; |
707 |
< |
if (w != null) |
708 |
< |
w.setUncaughtExceptionHandler(h); |
709 |
< |
} |
710 |
< |
} |
711 |
< |
} finally { |
712 |
< |
lock.unlock(); |
713 |
< |
} |
714 |
< |
return old; |
715 |
< |
} |
716 |
< |
|
717 |
< |
|
718 |
< |
/** |
719 |
< |
* Sets the target paralleism level of this pool. |
720 |
< |
* @param parallelism the target parallelism |
721 |
< |
* @throws IllegalArgumentException if parallelism less than or |
722 |
< |
* equal to zero or greater than maximum size bounds. |
723 |
< |
* @throws SecurityException if a security manager exists and |
724 |
< |
* the caller is not permitted to modify threads |
725 |
< |
* because it does not hold {@link |
726 |
< |
* java.lang.RuntimePermission}<code>("modifyThread")</code>, |
727 |
< |
*/ |
728 |
< |
public void setParallelism(int parallelism) { |
729 |
< |
checkPermission(); |
730 |
< |
if (parallelism <= 0 || parallelism > maxPoolSize) |
731 |
< |
throw new IllegalArgumentException(); |
732 |
< |
final ReentrantLock lock = this.workerLock; |
733 |
< |
lock.lock(); |
734 |
< |
try { |
735 |
< |
if (!isTerminating()) { |
736 |
< |
int p = this.parallelism; |
737 |
< |
this.parallelism = parallelism; |
738 |
< |
if (parallelism > p) |
739 |
< |
createAndStartAddedWorkers(); |
740 |
< |
else |
741 |
< |
trimSpares(); |
742 |
< |
} |
743 |
< |
} finally { |
744 |
< |
lock.unlock(); |
745 |
< |
} |
746 |
< |
signalIdleWorkers(); |
2131 |
> |
public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() { |
2132 |
> |
return ueh; |
2133 |
|
} |
2134 |
|
|
2135 |
|
/** |
2136 |
< |
* Returns the targeted number of worker threads in this pool. |
2136 |
> |
* Returns the targeted parallelism level of this pool. |
2137 |
|
* |
2138 |
< |
* @return the targeted number of worker threads in this pool |
2138 |
> |
* @return the targeted parallelism level of this pool |
2139 |
|
*/ |
2140 |
|
public int getParallelism() { |
2141 |
|
return parallelism; |
2143 |
|
|
2144 |
|
/** |
2145 |
|
* Returns the number of worker threads that have started but not |
2146 |
< |
* yet terminated. This result returned by this method may differ |
2147 |
< |
* from <code>getParallelism</code> when threads are created to |
2146 |
> |
* yet terminated. The result returned by this method may differ |
2147 |
> |
* from {@link #getParallelism} when threads are created to |
2148 |
|
* maintain parallelism when others are cooperatively blocked. |
2149 |
|
* |
2150 |
|
* @return the number of worker threads |
2151 |
|
*/ |
2152 |
|
public int getPoolSize() { |
2153 |
< |
return totalCountOf(workerCounts); |
2153 |
> |
return parallelism + (short)(ctl >>> TC_SHIFT); |
2154 |
|
} |
2155 |
|
|
2156 |
|
/** |
2157 |
< |
* Returns the maximum number of threads allowed to exist in the |
2158 |
< |
* pool, even if there are insufficient unblocked running threads. |
773 |
< |
* @return the maximum |
774 |
< |
*/ |
775 |
< |
public int getMaximumPoolSize() { |
776 |
< |
return maxPoolSize; |
777 |
< |
} |
778 |
< |
|
779 |
< |
/** |
780 |
< |
* Sets the maximum number of threads allowed to exist in the |
781 |
< |
* pool, even if there are insufficient unblocked running threads. |
782 |
< |
* Setting this value has no effect on current pool size. It |
783 |
< |
* controls construction of new threads. |
784 |
< |
* @throws IllegalArgumentException if negative or greater then |
785 |
< |
* internal implementation limit. |
786 |
< |
*/ |
787 |
< |
public void setMaximumPoolSize(int newMax) { |
788 |
< |
if (newMax < 0 || newMax > MAX_THREADS) |
789 |
< |
throw new IllegalArgumentException(); |
790 |
< |
maxPoolSize = newMax; |
791 |
< |
} |
792 |
< |
|
793 |
< |
|
794 |
< |
/** |
795 |
< |
* Returns true if this pool dynamically maintains its target |
796 |
< |
* parallelism level. If false, new threads are added only to |
797 |
< |
* avoid possible starvation. |
798 |
< |
* This setting is by default true; |
799 |
< |
* @return true if maintains parallelism |
800 |
< |
*/ |
801 |
< |
public boolean getMaintainsParallelism() { |
802 |
< |
return maintainsParallelism; |
803 |
< |
} |
804 |
< |
|
805 |
< |
/** |
806 |
< |
* Sets whether this pool dynamically maintains its target |
807 |
< |
* parallelism level. If false, new threads are added only to |
808 |
< |
* avoid possible starvation. |
809 |
< |
* @param enable true to maintains parallelism |
810 |
< |
*/ |
811 |
< |
public void setMaintainsParallelism(boolean enable) { |
812 |
< |
maintainsParallelism = enable; |
813 |
< |
} |
814 |
< |
|
815 |
< |
/** |
816 |
< |
* Establishes local first-in-first-out scheduling mode for forked |
817 |
< |
* tasks that are never joined. This mode may be more appropriate |
818 |
< |
* than default locally stack-based mode in applications in which |
819 |
< |
* worker threads only process asynchronous tasks. This method is |
820 |
< |
* designed to be invoked only when pool is quiescent, and |
821 |
< |
* typically only before any tasks are submitted. The effects of |
822 |
< |
* invocations at ather times may be unpredictable. |
823 |
< |
* |
824 |
< |
* @param async if true, use locally FIFO scheduling |
825 |
< |
* @return the previous mode. |
826 |
< |
*/ |
827 |
< |
public boolean setAsyncMode(boolean async) { |
828 |
< |
boolean oldMode = locallyFifo; |
829 |
< |
locallyFifo = async; |
830 |
< |
ForkJoinWorkerThread[] ws = workers; |
831 |
< |
if (ws != null) { |
832 |
< |
for (int i = 0; i < ws.length; ++i) { |
833 |
< |
ForkJoinWorkerThread t = ws[i]; |
834 |
< |
if (t != null) |
835 |
< |
t.setAsyncMode(async); |
836 |
< |
} |
837 |
< |
} |
838 |
< |
return oldMode; |
839 |
< |
} |
840 |
< |
|
841 |
< |
/** |
842 |
< |
* Returns true if this pool uses local first-in-first-out |
843 |
< |
* scheduling mode for forked tasks that are never joined. |
2157 |
> |
* Returns {@code true} if this pool uses local first-in-first-out |
2158 |
> |
* scheduling mode for forked tasks that are never joined. |
2159 |
|
* |
2160 |
< |
* @return true if this pool uses async mode. |
2160 |
> |
* @return {@code true} if this pool uses async mode |
2161 |
|
*/ |
2162 |
|
public boolean getAsyncMode() { |
2163 |
< |
return locallyFifo; |
2163 |
> |
return localMode != 0; |
2164 |
|
} |
2165 |
|
|
2166 |
|
/** |
2167 |
|
* Returns an estimate of the number of worker threads that are |
2168 |
|
* not blocked waiting to join tasks or for other managed |
2169 |
< |
* synchronization. |
2169 |
> |
* synchronization. This method may overestimate the |
2170 |
> |
* number of running threads. |
2171 |
|
* |
2172 |
|
* @return the number of worker threads |
2173 |
|
*/ |
2174 |
|
public int getRunningThreadCount() { |
2175 |
< |
return runningCountOf(workerCounts); |
2175 |
> |
int rc = 0; |
2176 |
> |
WorkQueue[] ws; WorkQueue w; |
2177 |
> |
if ((ws = workQueues) != null) { |
2178 |
> |
int n = ws.length; |
2179 |
> |
for (int i = 1; i < n; i += 2) { |
2180 |
> |
Thread.State s; ForkJoinWorkerThread wt; |
2181 |
> |
if ((w = ws[i]) != null && (wt = w.owner) != null && |
2182 |
> |
w.eventCount >= 0 && |
2183 |
> |
(s = wt.getState()) != Thread.State.BLOCKED && |
2184 |
> |
s != Thread.State.WAITING && |
2185 |
> |
s != Thread.State.TIMED_WAITING) |
2186 |
> |
++rc; |
2187 |
> |
} |
2188 |
> |
} |
2189 |
> |
return rc; |
2190 |
|
} |
2191 |
|
|
2192 |
|
/** |
2193 |
|
* Returns an estimate of the number of threads that are currently |
2194 |
|
* stealing or executing tasks. This method may overestimate the |
2195 |
|
* number of active threads. |
2196 |
< |
* @return the number of active threads. |
2196 |
> |
* |
2197 |
> |
* @return the number of active threads |
2198 |
|
*/ |
2199 |
|
public int getActiveThreadCount() { |
2200 |
< |
return activeCountOf(runControl); |
2201 |
< |
} |
871 |
< |
|
872 |
< |
/** |
873 |
< |
* Returns an estimate of the number of threads that are currently |
874 |
< |
* idle waiting for tasks. This method may underestimate the |
875 |
< |
* number of idle threads. |
876 |
< |
* @return the number of idle threads. |
877 |
< |
*/ |
878 |
< |
final int getIdleThreadCount() { |
879 |
< |
int c = runningCountOf(workerCounts) - activeCountOf(runControl); |
880 |
< |
return (c <= 0)? 0 : c; |
2200 |
> |
int r = parallelism + (int)(ctl >> AC_SHIFT); |
2201 |
> |
return (r <= 0) ? 0 : r; // suppress momentarily negative values |
2202 |
|
} |
2203 |
|
|
2204 |
|
/** |
2205 |
< |
* Returns true if all worker threads are currently idle. An idle |
2206 |
< |
* worker is one that cannot obtain a task to execute because none |
2207 |
< |
* are available to steal from other threads, and there are no |
2208 |
< |
* pending submissions to the pool. This method is conservative: |
2209 |
< |
* It might not return true immediately upon idleness of all |
2210 |
< |
* threads, but will eventually become true if threads remain |
2211 |
< |
* inactive. |
2212 |
< |
* @return true if all threads are currently idle |
2205 |
> |
* Returns {@code true} if all worker threads are currently idle. |
2206 |
> |
* An idle worker is one that cannot obtain a task to execute |
2207 |
> |
* because none are available to steal from other threads, and |
2208 |
> |
* there are no pending submissions to the pool. This method is |
2209 |
> |
* conservative; it might not return {@code true} immediately upon |
2210 |
> |
* idleness of all threads, but will eventually become true if |
2211 |
> |
* threads remain inactive. |
2212 |
> |
* |
2213 |
> |
* @return {@code true} if all threads are currently idle |
2214 |
|
*/ |
2215 |
|
public boolean isQuiescent() { |
2216 |
< |
return activeCountOf(runControl) == 0; |
2216 |
> |
return (int)(ctl >> AC_SHIFT) + parallelism == 0; |
2217 |
|
} |
2218 |
|
|
2219 |
|
/** |
2221 |
|
* one thread's work queue by another. The reported value |
2222 |
|
* underestimates the actual total number of steals when the pool |
2223 |
|
* is not quiescent. This value may be useful for monitoring and |
2224 |
< |
* tuning fork/join programs: In general, steal counts should be |
2224 |
> |
* tuning fork/join programs: in general, steal counts should be |
2225 |
|
* high enough to keep threads busy, but low enough to avoid |
2226 |
|
* overhead and contention across threads. |
2227 |
< |
* @return the number of steals. |
2227 |
> |
* |
2228 |
> |
* @return the number of steals |
2229 |
|
*/ |
2230 |
|
public long getStealCount() { |
2231 |
< |
return stealCount.get(); |
2232 |
< |
} |
2233 |
< |
|
2234 |
< |
/** |
2235 |
< |
* Accumulate steal count from a worker. Call only |
2236 |
< |
* when worker known to be idle. |
2237 |
< |
*/ |
2238 |
< |
private void updateStealCount(ForkJoinWorkerThread w) { |
2239 |
< |
int sc = w.getAndClearStealCount(); |
2240 |
< |
if (sc != 0) |
918 |
< |
stealCount.addAndGet(sc); |
2231 |
> |
long count = stealCount.get(); |
2232 |
> |
WorkQueue[] ws; WorkQueue w; |
2233 |
> |
if ((ws = workQueues) != null) { |
2234 |
> |
int n = ws.length; |
2235 |
> |
for (int i = 1; i < n; i += 2) { |
2236 |
> |
if ((w = ws[i]) != null) |
2237 |
> |
count += w.totalSteals; |
2238 |
> |
} |
2239 |
> |
} |
2240 |
> |
return count; |
2241 |
|
} |
2242 |
|
|
2243 |
|
/** |
2247 |
|
* an approximation, obtained by iterating across all threads in |
2248 |
|
* the pool. This method may be useful for tuning task |
2249 |
|
* granularities. |
2250 |
< |
* @return the number of queued tasks. |
2250 |
> |
* |
2251 |
> |
* @return the number of queued tasks |
2252 |
|
*/ |
2253 |
|
public long getQueuedTaskCount() { |
2254 |
|
long count = 0; |
2255 |
< |
ForkJoinWorkerThread[] ws = workers; |
2256 |
< |
if (ws != null) { |
2257 |
< |
for (int i = 0; i < ws.length; ++i) { |
2258 |
< |
ForkJoinWorkerThread t = ws[i]; |
2259 |
< |
if (t != null) |
2260 |
< |
count += t.getQueueSize(); |
2255 |
> |
WorkQueue[] ws; WorkQueue w; |
2256 |
> |
if ((ws = workQueues) != null) { |
2257 |
> |
int n = ws.length; |
2258 |
> |
for (int i = 1; i < n; i += 2) { |
2259 |
> |
if ((w = ws[i]) != null) |
2260 |
> |
count += w.queueSize(); |
2261 |
|
} |
2262 |
|
} |
2263 |
|
return count; |
2264 |
|
} |
2265 |
|
|
2266 |
|
/** |
2267 |
< |
* Returns an estimate of the number tasks submitted to this pool |
2268 |
< |
* that have not yet begun executing. This method takes time |
2269 |
< |
* proportional to the number of submissions. |
2270 |
< |
* @return the number of queued submissions. |
2267 |
> |
* Returns an estimate of the number of tasks submitted to this |
2268 |
> |
* pool that have not yet begun executing. This method may take |
2269 |
> |
* time proportional to the number of submissions. |
2270 |
> |
* |
2271 |
> |
* @return the number of queued submissions |
2272 |
|
*/ |
2273 |
|
public int getQueuedSubmissionCount() { |
2274 |
< |
return submissionQueue.size(); |
2274 |
> |
int count = 0; |
2275 |
> |
WorkQueue[] ws; WorkQueue w; |
2276 |
> |
if ((ws = workQueues) != null) { |
2277 |
> |
int n = ws.length; |
2278 |
> |
for (int i = 0; i < n; i += 2) { |
2279 |
> |
if ((w = ws[i]) != null) |
2280 |
> |
count += w.queueSize(); |
2281 |
> |
} |
2282 |
> |
} |
2283 |
> |
return count; |
2284 |
|
} |
2285 |
|
|
2286 |
|
/** |
2287 |
< |
* Returns true if there are any tasks submitted to this pool |
2288 |
< |
* that have not yet begun executing. |
2289 |
< |
* @return <code>true</code> if there are any queued submissions. |
2287 |
> |
* Returns {@code true} if there are any tasks submitted to this |
2288 |
> |
* pool that have not yet begun executing. |
2289 |
> |
* |
2290 |
> |
* @return {@code true} if there are any queued submissions |
2291 |
|
*/ |
2292 |
|
public boolean hasQueuedSubmissions() { |
2293 |
< |
return !submissionQueue.isEmpty(); |
2293 |
> |
WorkQueue[] ws; WorkQueue w; |
2294 |
> |
if ((ws = workQueues) != null) { |
2295 |
> |
int n = ws.length; |
2296 |
> |
for (int i = 0; i < n; i += 2) { |
2297 |
> |
if ((w = ws[i]) != null && w.queueSize() != 0) |
2298 |
> |
return true; |
2299 |
> |
} |
2300 |
> |
} |
2301 |
> |
return false; |
2302 |
|
} |
2303 |
|
|
2304 |
|
/** |
2305 |
|
* Removes and returns the next unexecuted submission if one is |
2306 |
|
* available. This method may be useful in extensions to this |
2307 |
|
* class that re-assign work in systems with multiple pools. |
2308 |
< |
* @return the next submission, or null if none |
2308 |
> |
* |
2309 |
> |
* @return the next submission, or {@code null} if none |
2310 |
|
*/ |
2311 |
|
protected ForkJoinTask<?> pollSubmission() { |
2312 |
< |
return submissionQueue.poll(); |
2312 |
> |
WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t; |
2313 |
> |
if ((ws = workQueues) != null) { |
2314 |
> |
int n = ws.length; |
2315 |
> |
for (int i = 0; i < n; i += 2) { |
2316 |
> |
if ((w = ws[i]) != null && (t = w.poll()) != null) |
2317 |
> |
return t; |
2318 |
> |
} |
2319 |
> |
} |
2320 |
> |
return null; |
2321 |
|
} |
2322 |
|
|
2323 |
|
/** |
2324 |
|
* Removes all available unexecuted submitted and forked tasks |
2325 |
|
* from scheduling queues and adds them to the given collection, |
2326 |
|
* without altering their execution status. These may include |
2327 |
< |
* artifically generated or wrapped tasks. This method id designed |
2328 |
< |
* to be invoked only when the pool is known to be |
2327 |
> |
* artificially generated or wrapped tasks. This method is |
2328 |
> |
* designed to be invoked only when the pool is known to be |
2329 |
|
* quiescent. Invocations at other times may not remove all |
2330 |
|
* tasks. A failure encountered while attempting to add elements |
2331 |
< |
* to collection <tt>c</tt> may result in elements being in |
2331 |
> |
* to collection {@code c} may result in elements being in |
2332 |
|
* neither, either or both collections when the associated |
2333 |
|
* exception is thrown. The behavior of this operation is |
2334 |
|
* undefined if the specified collection is modified while the |
2335 |
|
* operation is in progress. |
2336 |
+ |
* |
2337 |
|
* @param c the collection to transfer elements into |
2338 |
|
* @return the number of elements transferred |
2339 |
|
*/ |
2340 |
< |
protected int drainTasksTo(Collection<ForkJoinTask<?>> c) { |
2341 |
< |
int n = submissionQueue.drainTo(c); |
2342 |
< |
ForkJoinWorkerThread[] ws = workers; |
2343 |
< |
if (ws != null) { |
2344 |
< |
for (int i = 0; i < ws.length; ++i) { |
2345 |
< |
ForkJoinWorkerThread w = ws[i]; |
2346 |
< |
if (w != null) |
2347 |
< |
n += w.drainTasksTo(c); |
2340 |
> |
protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) { |
2341 |
> |
int count = 0; |
2342 |
> |
WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t; |
2343 |
> |
if ((ws = workQueues) != null) { |
2344 |
> |
int n = ws.length; |
2345 |
> |
for (int i = 0; i < n; ++i) { |
2346 |
> |
if ((w = ws[i]) != null) { |
2347 |
> |
while ((t = w.poll()) != null) { |
2348 |
> |
c.add(t); |
2349 |
> |
++count; |
2350 |
> |
} |
2351 |
> |
} |
2352 |
|
} |
2353 |
|
} |
2354 |
< |
return n; |
2354 |
> |
return count; |
2355 |
|
} |
2356 |
|
|
2357 |
|
/** |
2362 |
|
* @return a string identifying this pool, as well as its state |
2363 |
|
*/ |
2364 |
|
public String toString() { |
1009 |
– |
int ps = parallelism; |
1010 |
– |
int wc = workerCounts; |
1011 |
– |
int rc = runControl; |
2365 |
|
long st = getStealCount(); |
2366 |
|
long qt = getQueuedTaskCount(); |
2367 |
|
long qs = getQueuedSubmissionCount(); |
2368 |
+ |
int rc = getRunningThreadCount(); |
2369 |
+ |
int pc = parallelism; |
2370 |
+ |
long c = ctl; |
2371 |
+ |
int tc = pc + (short)(c >>> TC_SHIFT); |
2372 |
+ |
int ac = pc + (int)(c >> AC_SHIFT); |
2373 |
+ |
if (ac < 0) // ignore transient negative |
2374 |
+ |
ac = 0; |
2375 |
+ |
String level; |
2376 |
+ |
if ((c & STOP_BIT) != 0) |
2377 |
+ |
level = (tc == 0) ? "Terminated" : "Terminating"; |
2378 |
+ |
else |
2379 |
+ |
level = runState < 0 ? "Shutting down" : "Running"; |
2380 |
|
return super.toString() + |
2381 |
< |
"[" + runStateToString(runStateOf(rc)) + |
2382 |
< |
", parallelism = " + ps + |
2383 |
< |
", size = " + totalCountOf(wc) + |
2384 |
< |
", active = " + activeCountOf(rc) + |
2385 |
< |
", running = " + runningCountOf(wc) + |
2381 |
> |
"[" + level + |
2382 |
> |
", parallelism = " + pc + |
2383 |
> |
", size = " + tc + |
2384 |
> |
", active = " + ac + |
2385 |
> |
", running = " + rc + |
2386 |
|
", steals = " + st + |
2387 |
|
", tasks = " + qt + |
2388 |
|
", submissions = " + qs + |
2389 |
|
"]"; |
2390 |
|
} |
2391 |
|
|
1027 |
– |
private static String runStateToString(int rs) { |
1028 |
– |
switch(rs) { |
1029 |
– |
case RUNNING: return "Running"; |
1030 |
– |
case SHUTDOWN: return "Shutting down"; |
1031 |
– |
case TERMINATING: return "Terminating"; |
1032 |
– |
case TERMINATED: return "Terminated"; |
1033 |
– |
default: throw new Error("Unknown run state"); |
1034 |
– |
} |
1035 |
– |
} |
1036 |
– |
|
1037 |
– |
// lifecycle control |
1038 |
– |
|
2392 |
|
/** |
2393 |
|
* Initiates an orderly shutdown in which previously submitted |
2394 |
|
* tasks are executed, but no new tasks will be accepted. |
2395 |
|
* Invocation has no additional effect if already shut down. |
2396 |
|
* Tasks that are in the process of being submitted concurrently |
2397 |
|
* during the course of this method may or may not be rejected. |
2398 |
+ |
* |
2399 |
|
* @throws SecurityException if a security manager exists and |
2400 |
|
* the caller is not permitted to modify threads |
2401 |
|
* because it does not hold {@link |
2402 |
< |
* java.lang.RuntimePermission}<code>("modifyThread")</code>, |
2402 |
> |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
2403 |
|
*/ |
2404 |
|
public void shutdown() { |
2405 |
|
checkPermission(); |
2406 |
< |
transitionRunStateTo(SHUTDOWN); |
2407 |
< |
if (canTerminateOnShutdown(runControl)) |
1054 |
< |
terminateOnShutdown(); |
2406 |
> |
enableShutdown(); |
2407 |
> |
tryTerminate(false); |
2408 |
|
} |
2409 |
|
|
2410 |
|
/** |
2411 |
< |
* Attempts to stop all actively executing tasks, and cancels all |
2412 |
< |
* waiting tasks. Tasks that are in the process of being |
2413 |
< |
* submitted or executed concurrently during the course of this |
2414 |
< |
* method may or may not be rejected. Unlike some other executors, |
2415 |
< |
* this method cancels rather than collects non-executed tasks |
2416 |
< |
* upon termination, so always returns an empty list. However, you |
2417 |
< |
* can use method <code>drainTasksTo</code> before invoking this |
2418 |
< |
* method to transfer unexecuted tasks to another collection. |
2411 |
> |
* Attempts to cancel and/or stop all tasks, and reject all |
2412 |
> |
* subsequently submitted tasks. Tasks that are in the process of |
2413 |
> |
* being submitted or executed concurrently during the course of |
2414 |
> |
* this method may or may not be rejected. This method cancels |
2415 |
> |
* both existing and unexecuted tasks, in order to permit |
2416 |
> |
* termination in the presence of task dependencies. So the method |
2417 |
> |
* always returns an empty list (unlike the case for some other |
2418 |
> |
* Executors). |
2419 |
> |
* |
2420 |
|
* @return an empty list |
2421 |
|
* @throws SecurityException if a security manager exists and |
2422 |
|
* the caller is not permitted to modify threads |
2423 |
|
* because it does not hold {@link |
2424 |
< |
* java.lang.RuntimePermission}<code>("modifyThread")</code>, |
2424 |
> |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
2425 |
|
*/ |
2426 |
|
public List<Runnable> shutdownNow() { |
2427 |
|
checkPermission(); |
2428 |
< |
terminate(); |
2428 |
> |
enableShutdown(); |
2429 |
> |
tryTerminate(true); |
2430 |
|
return Collections.emptyList(); |
2431 |
|
} |
2432 |
|
|
2433 |
|
/** |
2434 |
< |
* Returns <code>true</code> if all tasks have completed following shut down. |
2434 |
> |
* Returns {@code true} if all tasks have completed following shut down. |
2435 |
|
* |
2436 |
< |
* @return <code>true</code> if all tasks have completed following shut down |
2436 |
> |
* @return {@code true} if all tasks have completed following shut down |
2437 |
|
*/ |
2438 |
|
public boolean isTerminated() { |
2439 |
< |
return runStateOf(runControl) == TERMINATED; |
2439 |
> |
long c = ctl; |
2440 |
> |
return ((c & STOP_BIT) != 0L && |
2441 |
> |
(short)(c >>> TC_SHIFT) == -parallelism); |
2442 |
|
} |
2443 |
|
|
2444 |
|
/** |
2445 |
< |
* Returns <code>true</code> if the process of termination has |
2446 |
< |
* commenced but possibly not yet completed. |
2445 |
> |
* Returns {@code true} if the process of termination has |
2446 |
> |
* commenced but not yet completed. This method may be useful for |
2447 |
> |
* debugging. A return of {@code true} reported a sufficient |
2448 |
> |
* period after shutdown may indicate that submitted tasks have |
2449 |
> |
* ignored or suppressed interruption, or are waiting for IO, |
2450 |
> |
* causing this executor not to properly terminate. (See the |
2451 |
> |
* advisory notes for class {@link ForkJoinTask} stating that |
2452 |
> |
* tasks should not normally entail blocking operations. But if |
2453 |
> |
* they do, they must abort them on interrupt.) |
2454 |
|
* |
2455 |
< |
* @return <code>true</code> if terminating |
2455 |
> |
* @return {@code true} if terminating but not yet terminated |
2456 |
|
*/ |
2457 |
|
public boolean isTerminating() { |
2458 |
< |
return runStateOf(runControl) >= TERMINATING; |
2458 |
> |
long c = ctl; |
2459 |
> |
return ((c & STOP_BIT) != 0L && |
2460 |
> |
(short)(c >>> TC_SHIFT) != -parallelism); |
2461 |
|
} |
2462 |
|
|
2463 |
|
/** |
2464 |
< |
* Returns <code>true</code> if this pool has been shut down. |
2464 |
> |
* Returns {@code true} if this pool has been shut down. |
2465 |
|
* |
2466 |
< |
* @return <code>true</code> if this pool has been shut down |
2466 |
> |
* @return {@code true} if this pool has been shut down |
2467 |
|
*/ |
2468 |
|
public boolean isShutdown() { |
2469 |
< |
return runStateOf(runControl) >= SHUTDOWN; |
2469 |
> |
return runState < 0; |
2470 |
|
} |
2471 |
|
|
2472 |
|
/** |
2476 |
|
* |
2477 |
|
* @param timeout the maximum time to wait |
2478 |
|
* @param unit the time unit of the timeout argument |
2479 |
< |
* @return <code>true</code> if this executor terminated and |
2480 |
< |
* <code>false</code> if the timeout elapsed before termination |
2479 |
> |
* @return {@code true} if this executor terminated and |
2480 |
> |
* {@code false} if the timeout elapsed before termination |
2481 |
|
* @throws InterruptedException if interrupted while waiting |
2482 |
|
*/ |
2483 |
|
public boolean awaitTermination(long timeout, TimeUnit unit) |
2484 |
|
throws InterruptedException { |
2485 |
|
long nanos = unit.toNanos(timeout); |
2486 |
< |
final ReentrantLock lock = this.workerLock; |
2486 |
> |
final ReentrantLock lock = this.lock; |
2487 |
|
lock.lock(); |
2488 |
|
try { |
2489 |
|
for (;;) { |
2498 |
|
} |
2499 |
|
} |
2500 |
|
|
1135 |
– |
// Shutdown and termination support |
1136 |
– |
|
1137 |
– |
/** |
1138 |
– |
* Callback from terminating worker. Null out the corresponding |
1139 |
– |
* workers slot, and if terminating, try to terminate, else try to |
1140 |
– |
* shrink workers array. |
1141 |
– |
* @param w the worker |
1142 |
– |
*/ |
1143 |
– |
final void workerTerminated(ForkJoinWorkerThread w) { |
1144 |
– |
updateStealCount(w); |
1145 |
– |
updateWorkerCount(-1); |
1146 |
– |
final ReentrantLock lock = this.workerLock; |
1147 |
– |
lock.lock(); |
1148 |
– |
try { |
1149 |
– |
ForkJoinWorkerThread[] ws = workers; |
1150 |
– |
if (ws != null) { |
1151 |
– |
int idx = w.poolIndex; |
1152 |
– |
if (idx >= 0 && idx < ws.length && ws[idx] == w) |
1153 |
– |
ws[idx] = null; |
1154 |
– |
if (totalCountOf(workerCounts) == 0) { |
1155 |
– |
terminate(); // no-op if already terminating |
1156 |
– |
transitionRunStateTo(TERMINATED); |
1157 |
– |
termination.signalAll(); |
1158 |
– |
} |
1159 |
– |
else if (!isTerminating()) { |
1160 |
– |
tryShrinkWorkerArray(); |
1161 |
– |
tryResumeSpare(true); // allow replacement |
1162 |
– |
} |
1163 |
– |
} |
1164 |
– |
} finally { |
1165 |
– |
lock.unlock(); |
1166 |
– |
} |
1167 |
– |
signalIdleWorkers(); |
1168 |
– |
} |
1169 |
– |
|
2501 |
|
/** |
2502 |
< |
* Initiate termination. |
2503 |
< |
*/ |
1173 |
< |
private void terminate() { |
1174 |
< |
if (transitionRunStateTo(TERMINATING)) { |
1175 |
< |
stopAllWorkers(); |
1176 |
< |
resumeAllSpares(); |
1177 |
< |
signalIdleWorkers(); |
1178 |
< |
cancelQueuedSubmissions(); |
1179 |
< |
cancelQueuedWorkerTasks(); |
1180 |
< |
interruptUnterminatedWorkers(); |
1181 |
< |
signalIdleWorkers(); // resignal after interrupt |
1182 |
< |
} |
1183 |
< |
} |
1184 |
< |
|
1185 |
< |
/** |
1186 |
< |
* Possibly terminate when on shutdown state |
1187 |
< |
*/ |
1188 |
< |
private void terminateOnShutdown() { |
1189 |
< |
if (!hasQueuedSubmissions() && canTerminateOnShutdown(runControl)) |
1190 |
< |
terminate(); |
1191 |
< |
} |
1192 |
< |
|
1193 |
< |
/** |
1194 |
< |
* Clear out and cancel submissions |
1195 |
< |
*/ |
1196 |
< |
private void cancelQueuedSubmissions() { |
1197 |
< |
ForkJoinTask<?> task; |
1198 |
< |
while ((task = pollSubmission()) != null) |
1199 |
< |
task.cancel(false); |
1200 |
< |
} |
1201 |
< |
|
1202 |
< |
/** |
1203 |
< |
* Clean out worker queues. |
1204 |
< |
*/ |
1205 |
< |
private void cancelQueuedWorkerTasks() { |
1206 |
< |
final ReentrantLock lock = this.workerLock; |
1207 |
< |
lock.lock(); |
1208 |
< |
try { |
1209 |
< |
ForkJoinWorkerThread[] ws = workers; |
1210 |
< |
if (ws != null) { |
1211 |
< |
for (int i = 0; i < ws.length; ++i) { |
1212 |
< |
ForkJoinWorkerThread t = ws[i]; |
1213 |
< |
if (t != null) |
1214 |
< |
t.cancelTasks(); |
1215 |
< |
} |
1216 |
< |
} |
1217 |
< |
} finally { |
1218 |
< |
lock.unlock(); |
1219 |
< |
} |
1220 |
< |
} |
1221 |
< |
|
1222 |
< |
/** |
1223 |
< |
* Set each worker's status to terminating. Requires lock to avoid |
1224 |
< |
* conflicts with add/remove |
1225 |
< |
*/ |
1226 |
< |
private void stopAllWorkers() { |
1227 |
< |
final ReentrantLock lock = this.workerLock; |
1228 |
< |
lock.lock(); |
1229 |
< |
try { |
1230 |
< |
ForkJoinWorkerThread[] ws = workers; |
1231 |
< |
if (ws != null) { |
1232 |
< |
for (int i = 0; i < ws.length; ++i) { |
1233 |
< |
ForkJoinWorkerThread t = ws[i]; |
1234 |
< |
if (t != null) |
1235 |
< |
t.shutdownNow(); |
1236 |
< |
} |
1237 |
< |
} |
1238 |
< |
} finally { |
1239 |
< |
lock.unlock(); |
1240 |
< |
} |
1241 |
< |
} |
1242 |
< |
|
1243 |
< |
/** |
1244 |
< |
* Interrupt all unterminated workers. This is not required for |
1245 |
< |
* sake of internal control, but may help unstick user code during |
1246 |
< |
* shutdown. |
1247 |
< |
*/ |
1248 |
< |
private void interruptUnterminatedWorkers() { |
1249 |
< |
final ReentrantLock lock = this.workerLock; |
1250 |
< |
lock.lock(); |
1251 |
< |
try { |
1252 |
< |
ForkJoinWorkerThread[] ws = workers; |
1253 |
< |
if (ws != null) { |
1254 |
< |
for (int i = 0; i < ws.length; ++i) { |
1255 |
< |
ForkJoinWorkerThread t = ws[i]; |
1256 |
< |
if (t != null && !t.isTerminated()) { |
1257 |
< |
try { |
1258 |
< |
t.interrupt(); |
1259 |
< |
} catch (SecurityException ignore) { |
1260 |
< |
} |
1261 |
< |
} |
1262 |
< |
} |
1263 |
< |
} |
1264 |
< |
} finally { |
1265 |
< |
lock.unlock(); |
1266 |
< |
} |
1267 |
< |
} |
1268 |
< |
|
1269 |
< |
|
1270 |
< |
/* |
1271 |
< |
* Nodes for event barrier to manage idle threads. Queue nodes |
1272 |
< |
* are basic Treiber stack nodes, also used for spare stack. |
1273 |
< |
* |
1274 |
< |
* The event barrier has an event count and a wait queue (actually |
1275 |
< |
* a Treiber stack). Workers are enabled to look for work when |
1276 |
< |
* the eventCount is incremented. If they fail to find work, they |
1277 |
< |
* may wait for next count. Upon release, threads help others wake |
1278 |
< |
* up. |
1279 |
< |
* |
1280 |
< |
* Synchronization events occur only in enough contexts to |
1281 |
< |
* maintain overall liveness: |
1282 |
< |
* |
1283 |
< |
* - Submission of a new task to the pool |
1284 |
< |
* - Resizes or other changes to the workers array |
1285 |
< |
* - pool termination |
1286 |
< |
* - A worker pushing a task on an empty queue |
2502 |
> |
* Interface for extending managed parallelism for tasks running |
2503 |
> |
* in {@link ForkJoinPool}s. |
2504 |
|
* |
2505 |
< |
* The case of pushing a task occurs often enough, and is heavy |
2506 |
< |
* enough compared to simple stack pushes, to require special |
2507 |
< |
* handling: Method signalWork returns without advancing count if |
2508 |
< |
* the queue appears to be empty. This would ordinarily result in |
2509 |
< |
* races causing some queued waiters not to be woken up. To avoid |
2510 |
< |
* this, the first worker enqueued in method sync (see |
2511 |
< |
* syncIsReleasable) rescans for tasks after being enqueued, and |
2512 |
< |
* helps signal if any are found. This works well because the |
2513 |
< |
* worker has nothing better to do, and so might as well help |
2514 |
< |
* alleviate the overhead and contention on the threads actually |
2515 |
< |
* doing work. Also, since event counts increments on task |
2516 |
< |
* availability exist to maintain liveness (rather than to force |
2517 |
< |
* refreshes etc), it is OK for callers to exit early if |
1301 |
< |
* contending with another signaller. |
1302 |
< |
*/ |
1303 |
< |
static final class WaitQueueNode { |
1304 |
< |
WaitQueueNode next; // only written before enqueued |
1305 |
< |
volatile ForkJoinWorkerThread thread; // nulled to cancel wait |
1306 |
< |
final long count; // unused for spare stack |
1307 |
< |
|
1308 |
< |
WaitQueueNode(long c, ForkJoinWorkerThread w) { |
1309 |
< |
count = c; |
1310 |
< |
thread = w; |
1311 |
< |
} |
1312 |
< |
|
1313 |
< |
/** |
1314 |
< |
* Wake up waiter, returning false if known to already |
1315 |
< |
*/ |
1316 |
< |
boolean signal() { |
1317 |
< |
ForkJoinWorkerThread t = thread; |
1318 |
< |
if (t == null) |
1319 |
< |
return false; |
1320 |
< |
thread = null; |
1321 |
< |
LockSupport.unpark(t); |
1322 |
< |
return true; |
1323 |
< |
} |
1324 |
< |
|
1325 |
< |
/** |
1326 |
< |
* Await release on sync |
1327 |
< |
*/ |
1328 |
< |
void awaitSyncRelease(ForkJoinPool p) { |
1329 |
< |
while (thread != null && !p.syncIsReleasable(this)) |
1330 |
< |
LockSupport.park(this); |
1331 |
< |
} |
1332 |
< |
|
1333 |
< |
/** |
1334 |
< |
* Await resumption as spare |
1335 |
< |
*/ |
1336 |
< |
void awaitSpareRelease() { |
1337 |
< |
while (thread != null) { |
1338 |
< |
if (!Thread.interrupted()) |
1339 |
< |
LockSupport.park(this); |
1340 |
< |
} |
1341 |
< |
} |
1342 |
< |
} |
1343 |
< |
|
1344 |
< |
/** |
1345 |
< |
* Ensures that no thread is waiting for count to advance from the |
1346 |
< |
* current value of eventCount read on entry to this method, by |
1347 |
< |
* releasing waiting threads if necessary. |
1348 |
< |
* @return the count |
1349 |
< |
*/ |
1350 |
< |
final long ensureSync() { |
1351 |
< |
long c = eventCount; |
1352 |
< |
WaitQueueNode q; |
1353 |
< |
while ((q = syncStack) != null && q.count < c) { |
1354 |
< |
if (casBarrierStack(q, null)) { |
1355 |
< |
do { |
1356 |
< |
q.signal(); |
1357 |
< |
} while ((q = q.next) != null); |
1358 |
< |
break; |
1359 |
< |
} |
1360 |
< |
} |
1361 |
< |
return c; |
1362 |
< |
} |
1363 |
< |
|
1364 |
< |
/** |
1365 |
< |
* Increments event count and releases waiting threads. |
1366 |
< |
*/ |
1367 |
< |
private void signalIdleWorkers() { |
1368 |
< |
long c; |
1369 |
< |
do;while (!casEventCount(c = eventCount, c+1)); |
1370 |
< |
ensureSync(); |
1371 |
< |
} |
1372 |
< |
|
1373 |
< |
/** |
1374 |
< |
* Signal threads waiting to poll a task. Because method sync |
1375 |
< |
* rechecks availability, it is OK to only proceed if queue |
1376 |
< |
* appears to be non-empty, and OK to skip under contention to |
1377 |
< |
* increment count (since some other thread succeeded). |
1378 |
< |
*/ |
1379 |
< |
final void signalWork() { |
1380 |
< |
long c; |
1381 |
< |
WaitQueueNode q; |
1382 |
< |
if (syncStack != null && |
1383 |
< |
casEventCount(c = eventCount, c+1) && |
1384 |
< |
(((q = syncStack) != null && q.count <= c) && |
1385 |
< |
(!casBarrierStack(q, q.next) || !q.signal()))) |
1386 |
< |
ensureSync(); |
1387 |
< |
} |
1388 |
< |
|
1389 |
< |
/** |
1390 |
< |
* Waits until event count advances from last value held by |
1391 |
< |
* caller, or if excess threads, caller is resumed as spare, or |
1392 |
< |
* caller or pool is terminating. Updates caller's event on exit. |
1393 |
< |
* @param w the calling worker thread |
1394 |
< |
*/ |
1395 |
< |
final void sync(ForkJoinWorkerThread w) { |
1396 |
< |
updateStealCount(w); // Transfer w's count while it is idle |
1397 |
< |
|
1398 |
< |
while (!w.isShutdown() && !isTerminating() && !suspendIfSpare(w)) { |
1399 |
< |
long prev = w.lastEventCount; |
1400 |
< |
WaitQueueNode node = null; |
1401 |
< |
WaitQueueNode h; |
1402 |
< |
while (eventCount == prev && |
1403 |
< |
((h = syncStack) == null || h.count == prev)) { |
1404 |
< |
if (node == null) |
1405 |
< |
node = new WaitQueueNode(prev, w); |
1406 |
< |
if (casBarrierStack(node.next = h, node)) { |
1407 |
< |
node.awaitSyncRelease(this); |
1408 |
< |
break; |
1409 |
< |
} |
1410 |
< |
} |
1411 |
< |
long ec = ensureSync(); |
1412 |
< |
if (ec != prev) { |
1413 |
< |
w.lastEventCount = ec; |
1414 |
< |
break; |
1415 |
< |
} |
1416 |
< |
} |
1417 |
< |
} |
1418 |
< |
|
1419 |
< |
/** |
1420 |
< |
* Returns true if worker waiting on sync can proceed: |
1421 |
< |
* - on signal (thread == null) |
1422 |
< |
* - on event count advance (winning race to notify vs signaller) |
1423 |
< |
* - on Interrupt |
1424 |
< |
* - if the first queued node, we find work available |
1425 |
< |
* If node was not signalled and event count not advanced on exit, |
1426 |
< |
* then we also help advance event count. |
1427 |
< |
* @return true if node can be released |
1428 |
< |
*/ |
1429 |
< |
final boolean syncIsReleasable(WaitQueueNode node) { |
1430 |
< |
long prev = node.count; |
1431 |
< |
if (!Thread.interrupted() && node.thread != null && |
1432 |
< |
(node.next != null || |
1433 |
< |
!ForkJoinWorkerThread.hasQueuedTasks(workers)) && |
1434 |
< |
eventCount == prev) |
1435 |
< |
return false; |
1436 |
< |
if (node.thread != null) { |
1437 |
< |
node.thread = null; |
1438 |
< |
long ec = eventCount; |
1439 |
< |
if (prev <= ec) // help signal |
1440 |
< |
casEventCount(ec, ec+1); |
1441 |
< |
} |
1442 |
< |
return true; |
1443 |
< |
} |
1444 |
< |
|
1445 |
< |
/** |
1446 |
< |
* Returns true if a new sync event occurred since last call to |
1447 |
< |
* sync or this method, if so, updating caller's count. |
1448 |
< |
*/ |
1449 |
< |
final boolean hasNewSyncEvent(ForkJoinWorkerThread w) { |
1450 |
< |
long lc = w.lastEventCount; |
1451 |
< |
long ec = ensureSync(); |
1452 |
< |
if (ec == lc) |
1453 |
< |
return false; |
1454 |
< |
w.lastEventCount = ec; |
1455 |
< |
return true; |
1456 |
< |
} |
1457 |
< |
|
1458 |
< |
// Parallelism maintenance |
1459 |
< |
|
1460 |
< |
/** |
1461 |
< |
* Decrement running count; if too low, add spare. |
2505 |
> |
* <p>A {@code ManagedBlocker} provides two methods. Method |
2506 |
> |
* {@code isReleasable} must return {@code true} if blocking is |
2507 |
> |
* not necessary. Method {@code block} blocks the current thread |
2508 |
> |
* if necessary (perhaps internally invoking {@code isReleasable} |
2509 |
> |
* before actually blocking). These actions are performed by any |
2510 |
> |
* thread invoking {@link ForkJoinPool#managedBlock}. The |
2511 |
> |
* unusual methods in this API accommodate synchronizers that may, |
2512 |
> |
* but don't usually, block for long periods. Similarly, they |
2513 |
> |
* allow more efficient internal handling of cases in which |
2514 |
> |
* additional workers may be, but usually are not, needed to |
2515 |
> |
* ensure sufficient parallelism. Toward this end, |
2516 |
> |
* implementations of method {@code isReleasable} must be amenable |
2517 |
> |
* to repeated invocation. |
2518 |
|
* |
1463 |
– |
* Conceptually, all we need to do here is add or resume a |
1464 |
– |
* spare thread when one is about to block (and remove or |
1465 |
– |
* suspend it later when unblocked -- see suspendIfSpare). |
1466 |
– |
* However, implementing this idea requires coping with |
1467 |
– |
* several problems: We have imperfect information about the |
1468 |
– |
* states of threads. Some count updates can and usually do |
1469 |
– |
* lag run state changes, despite arrangements to keep them |
1470 |
– |
* accurate (for example, when possible, updating counts |
1471 |
– |
* before signalling or resuming), especially when running on |
1472 |
– |
* dynamic JVMs that don't optimize the infrequent paths that |
1473 |
– |
* update counts. Generating too many threads can make these |
1474 |
– |
* problems become worse, because excess threads are more |
1475 |
– |
* likely to be context-switched with others, slowing them all |
1476 |
– |
* down, especially if there is no work available, so all are |
1477 |
– |
* busy scanning or idling. Also, excess spare threads can |
1478 |
– |
* only be suspended or removed when they are idle, not |
1479 |
– |
* immediately when they aren't needed. So adding threads will |
1480 |
– |
* raise parallelism level for longer than necessary. Also, |
1481 |
– |
* FJ applications often enounter highly transient peaks when |
1482 |
– |
* many threads are blocked joining, but for less time than it |
1483 |
– |
* takes to create or resume spares. |
1484 |
– |
* |
1485 |
– |
* @param joinMe if non-null, return early if done |
1486 |
– |
* @param maintainParallelism if true, try to stay within |
1487 |
– |
* target counts, else create only to avoid starvation |
1488 |
– |
* @return true if joinMe known to be done |
1489 |
– |
*/ |
1490 |
– |
final boolean preJoin(ForkJoinTask<?> joinMe, boolean maintainParallelism) { |
1491 |
– |
maintainParallelism &= maintainsParallelism; // overrride |
1492 |
– |
boolean dec = false; // true when running count decremented |
1493 |
– |
while (spareStack == null || !tryResumeSpare(dec)) { |
1494 |
– |
int counts = workerCounts; |
1495 |
– |
if (dec || (dec = casWorkerCounts(counts, --counts))) { // CAS cheat |
1496 |
– |
if (!needSpare(counts, maintainParallelism)) |
1497 |
– |
break; |
1498 |
– |
if (joinMe.status < 0) |
1499 |
– |
return true; |
1500 |
– |
if (tryAddSpare(counts)) |
1501 |
– |
break; |
1502 |
– |
} |
1503 |
– |
} |
1504 |
– |
return false; |
1505 |
– |
} |
1506 |
– |
|
1507 |
– |
/** |
1508 |
– |
* Same idea as preJoin |
1509 |
– |
*/ |
1510 |
– |
final boolean preBlock(ManagedBlocker blocker, boolean maintainParallelism){ |
1511 |
– |
maintainParallelism &= maintainsParallelism; |
1512 |
– |
boolean dec = false; |
1513 |
– |
while (spareStack == null || !tryResumeSpare(dec)) { |
1514 |
– |
int counts = workerCounts; |
1515 |
– |
if (dec || (dec = casWorkerCounts(counts, --counts))) { |
1516 |
– |
if (!needSpare(counts, maintainParallelism)) |
1517 |
– |
break; |
1518 |
– |
if (blocker.isReleasable()) |
1519 |
– |
return true; |
1520 |
– |
if (tryAddSpare(counts)) |
1521 |
– |
break; |
1522 |
– |
} |
1523 |
– |
} |
1524 |
– |
return false; |
1525 |
– |
} |
1526 |
– |
|
1527 |
– |
/** |
1528 |
– |
* Returns true if a spare thread appears to be needed. If |
1529 |
– |
* maintaining parallelism, returns true when the deficit in |
1530 |
– |
* running threads is more than the surplus of total threads, and |
1531 |
– |
* there is apparently some work to do. This self-limiting rule |
1532 |
– |
* means that the more threads that have already been added, the |
1533 |
– |
* less parallelism we will tolerate before adding another. |
1534 |
– |
* @param counts current worker counts |
1535 |
– |
* @param maintainParallelism try to maintain parallelism |
1536 |
– |
*/ |
1537 |
– |
private boolean needSpare(int counts, boolean maintainParallelism) { |
1538 |
– |
int ps = parallelism; |
1539 |
– |
int rc = runningCountOf(counts); |
1540 |
– |
int tc = totalCountOf(counts); |
1541 |
– |
int runningDeficit = ps - rc; |
1542 |
– |
int totalSurplus = tc - ps; |
1543 |
– |
return (tc < maxPoolSize && |
1544 |
– |
(rc == 0 || totalSurplus < 0 || |
1545 |
– |
(maintainParallelism && |
1546 |
– |
runningDeficit > totalSurplus && |
1547 |
– |
ForkJoinWorkerThread.hasQueuedTasks(workers)))); |
1548 |
– |
} |
1549 |
– |
|
1550 |
– |
/** |
1551 |
– |
* Add a spare worker if lock available and no more than the |
1552 |
– |
* expected numbers of threads exist |
1553 |
– |
* @return true if successful |
1554 |
– |
*/ |
1555 |
– |
private boolean tryAddSpare(int expectedCounts) { |
1556 |
– |
final ReentrantLock lock = this.workerLock; |
1557 |
– |
int expectedRunning = runningCountOf(expectedCounts); |
1558 |
– |
int expectedTotal = totalCountOf(expectedCounts); |
1559 |
– |
boolean success = false; |
1560 |
– |
boolean locked = false; |
1561 |
– |
// confirm counts while locking; CAS after obtaining lock |
1562 |
– |
try { |
1563 |
– |
for (;;) { |
1564 |
– |
int s = workerCounts; |
1565 |
– |
int tc = totalCountOf(s); |
1566 |
– |
int rc = runningCountOf(s); |
1567 |
– |
if (rc > expectedRunning || tc > expectedTotal) |
1568 |
– |
break; |
1569 |
– |
if (!locked && !(locked = lock.tryLock())) |
1570 |
– |
break; |
1571 |
– |
if (casWorkerCounts(s, workerCountsFor(tc+1, rc+1))) { |
1572 |
– |
createAndStartSpare(tc); |
1573 |
– |
success = true; |
1574 |
– |
break; |
1575 |
– |
} |
1576 |
– |
} |
1577 |
– |
} finally { |
1578 |
– |
if (locked) |
1579 |
– |
lock.unlock(); |
1580 |
– |
} |
1581 |
– |
return success; |
1582 |
– |
} |
1583 |
– |
|
1584 |
– |
/** |
1585 |
– |
* Add the kth spare worker. On entry, pool coounts are already |
1586 |
– |
* adjusted to reflect addition. |
1587 |
– |
*/ |
1588 |
– |
private void createAndStartSpare(int k) { |
1589 |
– |
ForkJoinWorkerThread w = null; |
1590 |
– |
ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(k + 1); |
1591 |
– |
int len = ws.length; |
1592 |
– |
// Probably, we can place at slot k. If not, find empty slot |
1593 |
– |
if (k < len && ws[k] != null) { |
1594 |
– |
for (k = 0; k < len && ws[k] != null; ++k) |
1595 |
– |
; |
1596 |
– |
} |
1597 |
– |
if (k < len && !isTerminating() && (w = createWorker(k)) != null) { |
1598 |
– |
ws[k] = w; |
1599 |
– |
w.start(); |
1600 |
– |
} |
1601 |
– |
else |
1602 |
– |
updateWorkerCount(-1); // adjust on failure |
1603 |
– |
signalIdleWorkers(); |
1604 |
– |
} |
1605 |
– |
|
1606 |
– |
/** |
1607 |
– |
* Suspend calling thread w if there are excess threads. Called |
1608 |
– |
* only from sync. Spares are enqueued in a Treiber stack |
1609 |
– |
* using the same WaitQueueNodes as barriers. They are resumed |
1610 |
– |
* mainly in preJoin, but are also woken on pool events that |
1611 |
– |
* require all threads to check run state. |
1612 |
– |
* @param w the caller |
1613 |
– |
*/ |
1614 |
– |
private boolean suspendIfSpare(ForkJoinWorkerThread w) { |
1615 |
– |
WaitQueueNode node = null; |
1616 |
– |
int s; |
1617 |
– |
while (parallelism < runningCountOf(s = workerCounts)) { |
1618 |
– |
if (node == null) |
1619 |
– |
node = new WaitQueueNode(0, w); |
1620 |
– |
if (casWorkerCounts(s, s-1)) { // representation-dependent |
1621 |
– |
// push onto stack |
1622 |
– |
do;while (!casSpareStack(node.next = spareStack, node)); |
1623 |
– |
// block until released by resumeSpare |
1624 |
– |
node.awaitSpareRelease(); |
1625 |
– |
return true; |
1626 |
– |
} |
1627 |
– |
} |
1628 |
– |
return false; |
1629 |
– |
} |
1630 |
– |
|
1631 |
– |
/** |
1632 |
– |
* Try to pop and resume a spare thread. |
1633 |
– |
* @param updateCount if true, increment running count on success |
1634 |
– |
* @return true if successful |
1635 |
– |
*/ |
1636 |
– |
private boolean tryResumeSpare(boolean updateCount) { |
1637 |
– |
WaitQueueNode q; |
1638 |
– |
while ((q = spareStack) != null) { |
1639 |
– |
if (casSpareStack(q, q.next)) { |
1640 |
– |
if (updateCount) |
1641 |
– |
updateRunningCount(1); |
1642 |
– |
q.signal(); |
1643 |
– |
return true; |
1644 |
– |
} |
1645 |
– |
} |
1646 |
– |
return false; |
1647 |
– |
} |
1648 |
– |
|
1649 |
– |
/** |
1650 |
– |
* Pop and resume all spare threads. Same idea as ensureSync. |
1651 |
– |
* @return true if any spares released |
1652 |
– |
*/ |
1653 |
– |
private boolean resumeAllSpares() { |
1654 |
– |
WaitQueueNode q; |
1655 |
– |
while ( (q = spareStack) != null) { |
1656 |
– |
if (casSpareStack(q, null)) { |
1657 |
– |
do { |
1658 |
– |
updateRunningCount(1); |
1659 |
– |
q.signal(); |
1660 |
– |
} while ((q = q.next) != null); |
1661 |
– |
return true; |
1662 |
– |
} |
1663 |
– |
} |
1664 |
– |
return false; |
1665 |
– |
} |
1666 |
– |
|
1667 |
– |
/** |
1668 |
– |
* Pop and shutdown excessive spare threads. Call only while |
1669 |
– |
* holding lock. This is not guaranteed to eliminate all excess |
1670 |
– |
* threads, only those suspended as spares, which are the ones |
1671 |
– |
* unlikely to be needed in the future. |
1672 |
– |
*/ |
1673 |
– |
private void trimSpares() { |
1674 |
– |
int surplus = totalCountOf(workerCounts) - parallelism; |
1675 |
– |
WaitQueueNode q; |
1676 |
– |
while (surplus > 0 && (q = spareStack) != null) { |
1677 |
– |
if (casSpareStack(q, null)) { |
1678 |
– |
do { |
1679 |
– |
updateRunningCount(1); |
1680 |
– |
ForkJoinWorkerThread w = q.thread; |
1681 |
– |
if (w != null && surplus > 0 && |
1682 |
– |
runningCountOf(workerCounts) > 0 && w.shutdown()) |
1683 |
– |
--surplus; |
1684 |
– |
q.signal(); |
1685 |
– |
} while ((q = q.next) != null); |
1686 |
– |
} |
1687 |
– |
} |
1688 |
– |
} |
1689 |
– |
|
1690 |
– |
/** |
1691 |
– |
* Interface for extending managed parallelism for tasks running |
1692 |
– |
* in ForkJoinPools. A ManagedBlocker provides two methods. |
1693 |
– |
* Method <code>isReleasable</code> must return true if blocking is not |
1694 |
– |
* necessary. Method <code>block</code> blocks the current thread |
1695 |
– |
* if necessary (perhaps internally invoking isReleasable before |
1696 |
– |
* actually blocking.). |
2519 |
|
* <p>For example, here is a ManagedBlocker based on a |
2520 |
|
* ReentrantLock: |
2521 |
< |
* <pre> |
2522 |
< |
* class ManagedLocker implements ManagedBlocker { |
2523 |
< |
* final ReentrantLock lock; |
2524 |
< |
* boolean hasLock = false; |
2525 |
< |
* ManagedLocker(ReentrantLock lock) { this.lock = lock; } |
2526 |
< |
* public boolean block() { |
2527 |
< |
* if (!hasLock) |
2528 |
< |
* lock.lock(); |
2529 |
< |
* return true; |
2530 |
< |
* } |
2531 |
< |
* public boolean isReleasable() { |
2532 |
< |
* return hasLock || (hasLock = lock.tryLock()); |
1711 |
< |
* } |
2521 |
> |
* <pre> {@code |
2522 |
> |
* class ManagedLocker implements ManagedBlocker { |
2523 |
> |
* final ReentrantLock lock; |
2524 |
> |
* boolean hasLock = false; |
2525 |
> |
* ManagedLocker(ReentrantLock lock) { this.lock = lock; } |
2526 |
> |
* public boolean block() { |
2527 |
> |
* if (!hasLock) |
2528 |
> |
* lock.lock(); |
2529 |
> |
* return true; |
2530 |
> |
* } |
2531 |
> |
* public boolean isReleasable() { |
2532 |
> |
* return hasLock || (hasLock = lock.tryLock()); |
2533 |
|
* } |
2534 |
< |
* </pre> |
2534 |
> |
* }}</pre> |
2535 |
> |
* |
2536 |
> |
* <p>Here is a class that possibly blocks waiting for an |
2537 |
> |
* item on a given queue: |
2538 |
> |
* <pre> {@code |
2539 |
> |
* class QueueTaker<E> implements ManagedBlocker { |
2540 |
> |
* final BlockingQueue<E> queue; |
2541 |
> |
* volatile E item = null; |
2542 |
> |
* QueueTaker(BlockingQueue<E> q) { this.queue = q; } |
2543 |
> |
* public boolean block() throws InterruptedException { |
2544 |
> |
* if (item == null) |
2545 |
> |
* item = queue.take(); |
2546 |
> |
* return true; |
2547 |
> |
* } |
2548 |
> |
* public boolean isReleasable() { |
2549 |
> |
* return item != null || (item = queue.poll()) != null; |
2550 |
> |
* } |
2551 |
> |
* public E getItem() { // call after pool.managedBlock completes |
2552 |
> |
* return item; |
2553 |
> |
* } |
2554 |
> |
* }}</pre> |
2555 |
|
*/ |
2556 |
|
public static interface ManagedBlocker { |
2557 |
|
/** |
2558 |
|
* Possibly blocks the current thread, for example waiting for |
2559 |
|
* a lock or condition. |
2560 |
< |
* @return true if no additional blocking is necessary (i.e., |
2561 |
< |
* if isReleasable would return true). |
2560 |
> |
* |
2561 |
> |
* @return {@code true} if no additional blocking is necessary |
2562 |
> |
* (i.e., if isReleasable would return true) |
2563 |
|
* @throws InterruptedException if interrupted while waiting |
2564 |
< |
* (the method is not required to do so, but is allowe to). |
2564 |
> |
* (the method is not required to do so, but is allowed to) |
2565 |
|
*/ |
2566 |
|
boolean block() throws InterruptedException; |
2567 |
|
|
2568 |
|
/** |
2569 |
< |
* Returns true if blocking is unnecessary. |
2569 |
> |
* Returns {@code true} if blocking is unnecessary. |
2570 |
|
*/ |
2571 |
|
boolean isReleasable(); |
2572 |
|
} |
2573 |
|
|
2574 |
|
/** |
2575 |
|
* Blocks in accord with the given blocker. If the current thread |
2576 |
< |
* is a ForkJoinWorkerThread, this method possibly arranges for a |
2577 |
< |
* spare thread to be activated if necessary to ensure parallelism |
2578 |
< |
* while the current thread is blocked. If |
2579 |
< |
* <code>maintainParallelism</code> is true and the pool supports |
2580 |
< |
* it ({@link #getMaintainsParallelism}), this method attempts to |
2581 |
< |
* maintain the pool's nominal parallelism. Otherwise if activates |
2582 |
< |
* a thread only if necessary to avoid complete starvation. This |
2583 |
< |
* option may be preferable when blockages use timeouts, or are |
2584 |
< |
* almost always brief. |
2585 |
< |
* |
2586 |
< |
* <p> If the caller is not a ForkJoinTask, this method is behaviorally |
2587 |
< |
* equivalent to |
2588 |
< |
* <pre> |
2589 |
< |
* while (!blocker.isReleasable()) |
1748 |
< |
* if (blocker.block()) |
1749 |
< |
* return; |
1750 |
< |
* </pre> |
1751 |
< |
* If the caller is a ForkJoinTask, then the pool may first |
1752 |
< |
* be expanded to ensure parallelism, and later adjusted. |
2576 |
> |
* is a {@link ForkJoinWorkerThread}, this method possibly |
2577 |
> |
* arranges for a spare thread to be activated if necessary to |
2578 |
> |
* ensure sufficient parallelism while the current thread is blocked. |
2579 |
> |
* |
2580 |
> |
* <p>If the caller is not a {@link ForkJoinTask}, this method is |
2581 |
> |
* behaviorally equivalent to |
2582 |
> |
* <pre> {@code |
2583 |
> |
* while (!blocker.isReleasable()) |
2584 |
> |
* if (blocker.block()) |
2585 |
> |
* return; |
2586 |
> |
* }</pre> |
2587 |
> |
* |
2588 |
> |
* If the caller is a {@code ForkJoinTask}, then the pool may |
2589 |
> |
* first be expanded to ensure parallelism, and later adjusted. |
2590 |
|
* |
2591 |
|
* @param blocker the blocker |
2592 |
< |
* @param maintainParallelism if true and supported by this pool, |
1756 |
< |
* attempt to maintain the pool's nominal parallelism; otherwise |
1757 |
< |
* activate a thread only if necessary to avoid complete |
1758 |
< |
* starvation. |
1759 |
< |
* @throws InterruptedException if blocker.block did so. |
2592 |
> |
* @throws InterruptedException if blocker.block did so |
2593 |
|
*/ |
2594 |
< |
public static void managedBlock(ManagedBlocker blocker, |
1762 |
< |
boolean maintainParallelism) |
2594 |
> |
public static void managedBlock(ManagedBlocker blocker) |
2595 |
|
throws InterruptedException { |
2596 |
|
Thread t = Thread.currentThread(); |
2597 |
< |
ForkJoinPool pool = (t instanceof ForkJoinWorkerThread? |
2598 |
< |
((ForkJoinWorkerThread)t).pool : null); |
2599 |
< |
if (!blocker.isReleasable()) { |
2600 |
< |
try { |
2601 |
< |
if (pool == null || |
2602 |
< |
!pool.preBlock(blocker, maintainParallelism)) |
2603 |
< |
awaitBlocker(blocker); |
2604 |
< |
} finally { |
2605 |
< |
if (pool != null) |
2606 |
< |
pool.updateRunningCount(1); |
2597 |
> |
ForkJoinPool p = ((t instanceof ForkJoinWorkerThread) ? |
2598 |
> |
((ForkJoinWorkerThread)t).pool : null); |
2599 |
> |
while (!blocker.isReleasable()) { |
2600 |
> |
if (p == null || p.tryCompensate()) { |
2601 |
> |
try { |
2602 |
> |
do {} while (!blocker.isReleasable() && !blocker.block()); |
2603 |
> |
} finally { |
2604 |
> |
if (p != null) |
2605 |
> |
p.incrementActiveCount(); |
2606 |
> |
} |
2607 |
> |
break; |
2608 |
|
} |
2609 |
|
} |
2610 |
|
} |
2611 |
|
|
2612 |
< |
private static void awaitBlocker(ManagedBlocker blocker) |
2613 |
< |
throws InterruptedException { |
2614 |
< |
do;while (!blocker.isReleasable() && !blocker.block()); |
1782 |
< |
} |
1783 |
< |
|
1784 |
< |
// AbstractExecutorService overrides |
2612 |
> |
// AbstractExecutorService overrides. These rely on undocumented |
2613 |
> |
// fact that ForkJoinTask.adapt returns ForkJoinTasks that also |
2614 |
> |
// implement RunnableFuture. |
2615 |
|
|
2616 |
|
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) { |
2617 |
< |
return new AdaptedRunnable(runnable, value); |
2617 |
> |
return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value); |
2618 |
|
} |
2619 |
|
|
2620 |
|
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) { |
2621 |
< |
return new AdaptedCallable(callable); |
2621 |
> |
return (RunnableFuture<T>) ForkJoinTask.adapt(callable); |
2622 |
|
} |
2623 |
|
|
2624 |
+ |
// Unsafe mechanics |
2625 |
+ |
private static final sun.misc.Unsafe U; |
2626 |
+ |
private static final long CTL; |
2627 |
+ |
private static final long RUNSTATE; |
2628 |
+ |
private static final long PARKBLOCKER; |
2629 |
|
|
2630 |
< |
// Temporary Unsafe mechanics for preliminary release |
2631 |
< |
private static Unsafe getUnsafe() throws Throwable { |
2630 |
> |
static { |
2631 |
> |
poolNumberGenerator = new AtomicInteger(); |
2632 |
> |
modifyThreadPermission = new RuntimePermission("modifyThread"); |
2633 |
> |
defaultForkJoinWorkerThreadFactory = |
2634 |
> |
new DefaultForkJoinWorkerThreadFactory(); |
2635 |
> |
int s; |
2636 |
|
try { |
2637 |
< |
return Unsafe.getUnsafe(); |
2637 |
> |
U = getUnsafe(); |
2638 |
> |
Class<?> k = ForkJoinPool.class; |
2639 |
> |
Class<?> tk = Thread.class; |
2640 |
> |
CTL = U.objectFieldOffset |
2641 |
> |
(k.getDeclaredField("ctl")); |
2642 |
> |
RUNSTATE = U.objectFieldOffset |
2643 |
> |
(k.getDeclaredField("runState")); |
2644 |
> |
PARKBLOCKER = U.objectFieldOffset |
2645 |
> |
(tk.getDeclaredField("parkBlocker")); |
2646 |
> |
} catch (Exception e) { |
2647 |
> |
throw new Error(e); |
2648 |
> |
} |
2649 |
> |
} |
2650 |
> |
|
2651 |
> |
/** |
2652 |
> |
* Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. |
2653 |
> |
* Replace with a simple call to Unsafe.getUnsafe when integrating |
2654 |
> |
* into a jdk. |
2655 |
> |
* |
2656 |
> |
* @return a sun.misc.Unsafe |
2657 |
> |
*/ |
2658 |
> |
private static sun.misc.Unsafe getUnsafe() { |
2659 |
> |
try { |
2660 |
> |
return sun.misc.Unsafe.getUnsafe(); |
2661 |
|
} catch (SecurityException se) { |
2662 |
|
try { |
2663 |
|
return java.security.AccessController.doPrivileged |
2664 |
< |
(new java.security.PrivilegedExceptionAction<Unsafe>() { |
2665 |
< |
public Unsafe run() throws Exception { |
2666 |
< |
return getUnsafePrivileged(); |
2664 |
> |
(new java.security |
2665 |
> |
.PrivilegedExceptionAction<sun.misc.Unsafe>() { |
2666 |
> |
public sun.misc.Unsafe run() throws Exception { |
2667 |
> |
java.lang.reflect.Field f = sun.misc |
2668 |
> |
.Unsafe.class.getDeclaredField("theUnsafe"); |
2669 |
> |
f.setAccessible(true); |
2670 |
> |
return (sun.misc.Unsafe) f.get(null); |
2671 |
|
}}); |
2672 |
|
} catch (java.security.PrivilegedActionException e) { |
2673 |
< |
throw e.getCause(); |
2673 |
> |
throw new RuntimeException("Could not initialize intrinsics", |
2674 |
> |
e.getCause()); |
2675 |
|
} |
2676 |
|
} |
2677 |
|
} |
2678 |
|
|
1812 |
– |
private static Unsafe getUnsafePrivileged() |
1813 |
– |
throws NoSuchFieldException, IllegalAccessException { |
1814 |
– |
Field f = Unsafe.class.getDeclaredField("theUnsafe"); |
1815 |
– |
f.setAccessible(true); |
1816 |
– |
return (Unsafe) f.get(null); |
1817 |
– |
} |
1818 |
– |
|
1819 |
– |
private static long fieldOffset(String fieldName) |
1820 |
– |
throws NoSuchFieldException { |
1821 |
– |
return _unsafe.objectFieldOffset |
1822 |
– |
(ForkJoinPool.class.getDeclaredField(fieldName)); |
1823 |
– |
} |
1824 |
– |
|
1825 |
– |
static final Unsafe _unsafe; |
1826 |
– |
static final long eventCountOffset; |
1827 |
– |
static final long workerCountsOffset; |
1828 |
– |
static final long runControlOffset; |
1829 |
– |
static final long syncStackOffset; |
1830 |
– |
static final long spareStackOffset; |
1831 |
– |
|
1832 |
– |
static { |
1833 |
– |
try { |
1834 |
– |
_unsafe = getUnsafe(); |
1835 |
– |
eventCountOffset = fieldOffset("eventCount"); |
1836 |
– |
workerCountsOffset = fieldOffset("workerCounts"); |
1837 |
– |
runControlOffset = fieldOffset("runControl"); |
1838 |
– |
syncStackOffset = fieldOffset("syncStack"); |
1839 |
– |
spareStackOffset = fieldOffset("spareStack"); |
1840 |
– |
} catch (Throwable e) { |
1841 |
– |
throw new RuntimeException("Could not initialize intrinsics", e); |
1842 |
– |
} |
1843 |
– |
} |
1844 |
– |
|
1845 |
– |
private boolean casEventCount(long cmp, long val) { |
1846 |
– |
return _unsafe.compareAndSwapLong(this, eventCountOffset, cmp, val); |
1847 |
– |
} |
1848 |
– |
private boolean casWorkerCounts(int cmp, int val) { |
1849 |
– |
return _unsafe.compareAndSwapInt(this, workerCountsOffset, cmp, val); |
1850 |
– |
} |
1851 |
– |
private boolean casRunControl(int cmp, int val) { |
1852 |
– |
return _unsafe.compareAndSwapInt(this, runControlOffset, cmp, val); |
1853 |
– |
} |
1854 |
– |
private boolean casSpareStack(WaitQueueNode cmp, WaitQueueNode val) { |
1855 |
– |
return _unsafe.compareAndSwapObject(this, spareStackOffset, cmp, val); |
1856 |
– |
} |
1857 |
– |
private boolean casBarrierStack(WaitQueueNode cmp, WaitQueueNode val) { |
1858 |
– |
return _unsafe.compareAndSwapObject(this, syncStackOffset, cmp, val); |
1859 |
– |
} |
2679 |
|
} |