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 |
5 |
*/ |
6 |
|
7 |
package jsr166y; |
8 |
|
9 |
import java.util.concurrent.*; |
10 |
|
11 |
import java.util.ArrayList; |
12 |
import java.util.Arrays; |
13 |
import java.util.Collection; |
14 |
import java.util.Collections; |
15 |
import java.util.List; |
16 |
import java.util.concurrent.locks.LockSupport; |
17 |
import java.util.concurrent.locks.ReentrantLock; |
18 |
import java.util.concurrent.atomic.AtomicInteger; |
19 |
import java.util.concurrent.CountDownLatch; |
20 |
|
21 |
/** |
22 |
* An {@link ExecutorService} for running {@link ForkJoinTask}s. |
23 |
* A {@code ForkJoinPool} provides the entry point for submissions |
24 |
* from non-{@code ForkJoinTask}s, as well as management and |
25 |
* monitoring operations. |
26 |
* |
27 |
* <p>A {@code ForkJoinPool} differs from other kinds of {@link |
28 |
* ExecutorService} mainly by virtue of employing |
29 |
* <em>work-stealing</em>: all threads in the pool attempt to find and |
30 |
* execute subtasks created by other active tasks (eventually blocking |
31 |
* waiting for work if none exist). This enables efficient processing |
32 |
* when most tasks spawn other subtasks (as do most {@code |
33 |
* ForkJoinTask}s). A {@code ForkJoinPool} may also be used for mixed |
34 |
* execution of some plain {@code Runnable}- or {@code Callable}- |
35 |
* based activities along with {@code ForkJoinTask}s. When setting |
36 |
* {@linkplain #setAsyncMode async mode}, a {@code ForkJoinPool} may |
37 |
* also be appropriate for use with fine-grained tasks of any form |
38 |
* that are never joined. Otherwise, other {@code ExecutorService} |
39 |
* implementations are typically more appropriate choices. |
40 |
* |
41 |
* <p>A {@code ForkJoinPool} is constructed with a given target |
42 |
* parallelism level; by default, equal to the number of available |
43 |
* processors. Unless configured otherwise via {@link |
44 |
* #setMaintainsParallelism}, the pool attempts to maintain this |
45 |
* number of active (or available) threads by dynamically adding, |
46 |
* suspending, or resuming internal worker threads, even if some tasks |
47 |
* are stalled waiting to join others. However, no such adjustments |
48 |
* are performed in the face of blocked IO or other unmanaged |
49 |
* synchronization. The nested {@link ManagedBlocker} interface |
50 |
* enables extension of the kinds of synchronization accommodated. |
51 |
* The target parallelism level may also be changed dynamically |
52 |
* ({@link #setParallelism}). The total number of threads may be |
53 |
* limited using method {@link #setMaximumPoolSize}, in which case it |
54 |
* may become possible for the activities of a pool to stall due to |
55 |
* the lack of available threads to process new tasks. When the pool |
56 |
* is executing tasks, these and other configuration setting methods |
57 |
* may only gradually affect actual pool sizes. It is normally best |
58 |
* practice to invoke these methods only when the pool is known to be |
59 |
* quiescent. |
60 |
* |
61 |
* <p>In addition to execution and lifecycle control methods, this |
62 |
* class provides status check methods (for example |
63 |
* {@link #getStealCount}) that are intended to aid in developing, |
64 |
* tuning, and monitoring fork/join applications. Also, method |
65 |
* {@link #toString} returns indications of pool state in a |
66 |
* convenient form for informal monitoring. |
67 |
* |
68 |
* <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is |
69 |
* used for all parallel task execution in a program or subsystem. |
70 |
* Otherwise, use would not usually outweigh the construction and |
71 |
* bookkeeping overhead of creating a large set of threads. For |
72 |
* example, a common pool could be used for the {@code SortTasks} |
73 |
* illustrated in {@link RecursiveAction}. Because {@code |
74 |
* ForkJoinPool} uses threads in {@linkplain java.lang.Thread#isDaemon |
75 |
* daemon} mode, there is typically no need to explicitly {@link |
76 |
* #shutdown} such a pool upon program exit. |
77 |
* |
78 |
* <pre> |
79 |
* static final ForkJoinPool mainPool = new ForkJoinPool(); |
80 |
* ... |
81 |
* public void sort(long[] array) { |
82 |
* mainPool.invoke(new SortTask(array, 0, array.length)); |
83 |
* } |
84 |
* </pre> |
85 |
* |
86 |
* <p><b>Implementation notes</b>: This implementation restricts the |
87 |
* maximum number of running threads to 32767. Attempts to create |
88 |
* pools with greater than the maximum number result in |
89 |
* {@code IllegalArgumentException}. |
90 |
* |
91 |
* <p>This implementation rejects submitted tasks (that is, by throwing |
92 |
* {@link RejectedExecutionException}) only when the pool is shut down. |
93 |
* |
94 |
* @since 1.7 |
95 |
* @author Doug Lea |
96 |
*/ |
97 |
public class ForkJoinPool extends AbstractExecutorService { |
98 |
|
99 |
/* |
100 |
* Implementation Overview |
101 |
* |
102 |
* This class provides the central bookkeeping and control for a |
103 |
* set of worker threads: Submissions from non-FJ threads enter |
104 |
* into a submission queue. Workers take these tasks and typically |
105 |
* split them into subtasks that may be stolen by other workers. |
106 |
* The main work-stealing mechanics implemented in class |
107 |
* ForkJoinWorkerThread give first priority to processing tasks |
108 |
* from their own queues (LIFO or FIFO, depending on mode), then |
109 |
* to randomized FIFO steals of tasks in other worker queues, and |
110 |
* lastly to new submissions. These mechanics do not consider |
111 |
* affinities, loads, cache localities, etc, so rarely provide the |
112 |
* best possible performance on a given machine, but portably |
113 |
* provide good throughput by averaging over these factors. |
114 |
* (Further, even if we did try to use such information, we do not |
115 |
* usually have a basis for exploiting it. For example, some sets |
116 |
* of tasks profit from cache affinities, but others are harmed by |
117 |
* cache pollution effects.) |
118 |
* |
119 |
* The main throughput advantages of work-stealing stem from |
120 |
* decentralized control -- workers mostly steal tasks from each |
121 |
* other. We do not want to negate this by creating bottlenecks |
122 |
* implementing the management responsibilities of this class. So |
123 |
* we use a collection of techniques that avoid, reduce, or cope |
124 |
* well with contention. These entail several instances of |
125 |
* bit-packing into CASable fields to maintain only the minimally |
126 |
* required atomicity. To enable such packing, we restrict maximum |
127 |
* parallelism to (1<<15)-1 (enabling twice this to fit into a 16 |
128 |
* bit field), which is far in excess of normal operating range. |
129 |
* Even though updates to some of these bookkeeping fields do |
130 |
* sometimes contend with each other, they don't normally |
131 |
* cache-contend with updates to others enough to warrant memory |
132 |
* padding or isolation. So they are all held as fields of |
133 |
* ForkJoinPool objects. The main capabilities are as follows: |
134 |
* |
135 |
* 1. Creating and removing workers. Workers are recorded in the |
136 |
* "workers" array. This is an array as opposed to some other data |
137 |
* structure to support index-based random steals by workers. |
138 |
* Updates to the array recording new workers and unrecording |
139 |
* terminated ones are protected from each other by a lock |
140 |
* (workerLock) but the array is otherwise concurrently readable, |
141 |
* and accessed directly by workers. To simplify index-based |
142 |
* operations, the array size is always a power of two, and all |
143 |
* readers must tolerate null slots. Currently, all worker thread |
144 |
* creation is on-demand, triggered by task submissions, |
145 |
* replacement of terminated workers, and/or compensation for |
146 |
* blocked workers. However, all other support code is set up to |
147 |
* work with other policies. |
148 |
* |
149 |
* 2. Bookkeeping for dynamically adding and removing workers. We |
150 |
* maintain a given level of parallelism (or, if |
151 |
* maintainsParallelism is false, at least avoid starvation). When |
152 |
* some workers are known to be blocked (on joins or via |
153 |
* ManagedBlocker), we may create or resume others to take their |
154 |
* place until they unblock (see below). Implementing this |
155 |
* requires counts of the number of "running" threads (i.e., those |
156 |
* that are neither blocked nor artifically suspended) as well as |
157 |
* the total number. These two values are packed into one field, |
158 |
* "workerCounts" because we need accurate snapshots when deciding |
159 |
* to create, resume or suspend. To support these decisions, |
160 |
* updates to spare counts must be prospective (not |
161 |
* retrospective). For example, the running count is decremented |
162 |
* before blocking by a thread about to block as a spare, but |
163 |
* incremented by the thread about to unblock it. Updates upon |
164 |
* resumption ofr threads blocking in awaitJoin or awaitBlocker |
165 |
* cannot usually be prospective, so the running count is in |
166 |
* general an upper bound of the number of productively running |
167 |
* threads Updates to the workerCounts field sometimes transiently |
168 |
* encounter a fair amount of contention when join dependencies |
169 |
* are such that many threads block or unblock at about the same |
170 |
* time. We alleviate this by sometimes bundling updates (for |
171 |
* example blocking one thread on join and resuming a spare cancel |
172 |
* each other out), and in most other cases performing an |
173 |
* alternative action like releasing waiters or locating spares. |
174 |
* |
175 |
* 3. Maintaining global run state. The run state of the pool |
176 |
* consists of a runLevel (SHUTDOWN, TERMINATING, etc) similar to |
177 |
* those in other Executor implementations, as well as a count of |
178 |
* "active" workers -- those that are, or soon will be, or |
179 |
* recently were executing tasks. The runLevel and active count |
180 |
* are packed together in order to correctly trigger shutdown and |
181 |
* termination. Without care, active counts can be subject to very |
182 |
* high contention. We substantially reduce this contention by |
183 |
* relaxing update rules. A worker must claim active status |
184 |
* prospectively, by activating if it sees that a submitted or |
185 |
* stealable task exists (it may find after activating that the |
186 |
* task no longer exists). It stays active while processing this |
187 |
* task (if it exists) and any other local subtasks it produces, |
188 |
* until it cannot find any other tasks. It then tries |
189 |
* inactivating (see method preStep), but upon update contention |
190 |
* instead scans for more tasks, later retrying inactivation if it |
191 |
* doesn't find any. |
192 |
* |
193 |
* 4. Managing idle workers waiting for tasks. We cannot let |
194 |
* workers spin indefinitely scanning for tasks when none are |
195 |
* available. On the other hand, we must quickly prod them into |
196 |
* action when new tasks are submitted or generated. We |
197 |
* park/unpark these idle workers using an event-count scheme. |
198 |
* Field eventCount is incremented upon events that may enable |
199 |
* workers that previously could not find a task to now find one: |
200 |
* Submission of a new task to the pool, or another worker pushing |
201 |
* a task onto a previously empty queue. (We also use this |
202 |
* mechanism for termination and reconfiguration actions that |
203 |
* require wakeups of idle workers). Each worker maintains its |
204 |
* last known event count, and blocks when a scan for work did not |
205 |
* find a task AND its lastEventCount matches the current |
206 |
* eventCount. Waiting idle workers are recorded in a variant of |
207 |
* Treiber stack headed by field eventWaiters which, when nonzero, |
208 |
* encodes the thread index and count awaited for by the worker |
209 |
* thread most recently calling eventSync. This thread in turn has |
210 |
* a record (field nextEventWaiter) for the next waiting worker. |
211 |
* In addition to allowing simpler decisions about need for |
212 |
* wakeup, the event count bits in eventWaiters serve the role of |
213 |
* tags to avoid ABA errors in Treiber stacks. To reduce delays |
214 |
* in task diffusion, workers not otherwise occupied may invoke |
215 |
* method releaseWaiters, that removes and signals (unparks) |
216 |
* workers not waiting on current count. To minimize task |
217 |
* production stalls associate with signalling, any worker pushing |
218 |
* a task on an empty queue invokes the weaker method signalWork, |
219 |
* that only releases idle workers until it detects interference |
220 |
* by other threads trying to release, and lets them take |
221 |
* over. The net effect is a tree-like diffusion of signals, where |
222 |
* released threads (and possibly others) help with unparks. To |
223 |
* further reduce contention effects a bit, failed CASes to |
224 |
* increment field eventCount are tolerated without retries. |
225 |
* Conceptually they are merged into the same event, which is OK |
226 |
* when their only purpose is to enable workers to scan for work. |
227 |
* |
228 |
* 5. Managing suspension of extra workers. When a worker is about |
229 |
* to block waiting for a join (or via ManagedBlockers), we may |
230 |
* create a new thread to maintain parallelism level, or at least |
231 |
* avoid starvation (see below). Usually, extra threads are needed |
232 |
* for only very short periods, yet join dependencies are such |
233 |
* that we sometimes need them in bursts. Rather than create new |
234 |
* threads each time this happens, we suspend no-longer-needed |
235 |
* extra ones as "spares". For most purposes, we don't distinguish |
236 |
* "extra" spare threads from normal "core" threads: On each call |
237 |
* to preStep (the only point at which we can do this) a worker |
238 |
* checks to see if there are now too many running workers, and if |
239 |
* so, suspends itself. Methods awaitJoin and awaitBlocker look |
240 |
* for suspended threads to resume before considering creating a |
241 |
* new replacement. We don't need a special data structure to |
242 |
* maintain spares; simply scanning the workers array looking for |
243 |
* worker.isSuspended() is fine because the calling thread is |
244 |
* otherwise not doing anything useful anyway; we are at least as |
245 |
* happy if after locating a spare, the caller doesn't actually |
246 |
* block because the join is ready before we try to adjust and |
247 |
* compensate. Note that this is intrinsically racy. One thread |
248 |
* may become a spare at about the same time as another is |
249 |
* needlessly being created. We counteract this and related slop |
250 |
* in part by requiring resumed spares to immediately recheck (in |
251 |
* preStep) to see whether they they should re-suspend. The only |
252 |
* effective difference between "extra" and "core" threads is that |
253 |
* we allow the "extra" ones to time out and die if they are not |
254 |
* resumed within a keep-alive interval of a few seconds. This is |
255 |
* implemented mainly within ForkJoinWorkerThread, but requires |
256 |
* some coordination (isTrimmed() -- meaning killed while |
257 |
* suspended) to correctly maintain pool counts. |
258 |
* |
259 |
* 6. Deciding when to create new workers. The main dynamic |
260 |
* control in this class is deciding when to create extra threads, |
261 |
* in methods awaitJoin and awaitBlocker. We always |
262 |
* need to create one when the number of running threads becomes |
263 |
* zero. But because blocked joins are typically dependent, we |
264 |
* don't necessarily need or want one-to-one replacement. Using a |
265 |
* one-to-one compensation rule often leads to enough useless |
266 |
* overhead creating, suspending, resuming, and/or killing threads |
267 |
* to signficantly degrade throughput. We use a rule reflecting |
268 |
* the idea that, the more spare threads you already have, the |
269 |
* more evidence you need to create another one. The "evidence" |
270 |
* here takes two forms: (1) Using a creation threshold expressed |
271 |
* in terms of the current deficit -- target minus running |
272 |
* threads. To reduce flickering and drift around target values, |
273 |
* the relation is quadratic: adding a spare if (dc*dc)>=(sc*pc) |
274 |
* (where dc is deficit, sc is number of spare threads and pc is |
275 |
* target parallelism.) (2) Using a form of adaptive |
276 |
* spionning. requiring a number of threshold checks proportional |
277 |
* to the number of spare threads. This effectively reduces churn |
278 |
* at the price of systematically undershooting target parallelism |
279 |
* when many threads are blocked. However, biasing toward |
280 |
* undeshooting partially compensates for the above mechanics to |
281 |
* suspend extra threads, that normally lead to overshoot because |
282 |
* we can only suspend workers in-between top-level actions. It |
283 |
* also better copes with the fact that some of the methods in |
284 |
* this class tend to never become compiled (but are interpreted), |
285 |
* so some components of the entire set of controls might execute |
286 |
* many times faster than others. And similarly for cases where |
287 |
* the apparent lack of work is just due to GC stalls and other |
288 |
* transient system activity. |
289 |
* |
290 |
* 7. Maintaining other configuration parameters and monitoring |
291 |
* statistics. Updates to fields controlling parallelism level, |
292 |
* max size, etc can only meaningfully take effect for individual |
293 |
* threads upon their next top-level actions; i.e., between |
294 |
* stealing/running tasks/submission, which are separated by calls |
295 |
* to preStep. Memory ordering for these (assumed infrequent) |
296 |
* reconfiguration calls is ensured by using reads and writes to |
297 |
* volatile field workerCounts (that must be read in preStep anyway) |
298 |
* as "fences" -- user-level reads are preceded by reads of |
299 |
* workCounts, and writes are followed by no-op CAS to |
300 |
* workerCounts. The values reported by other management and |
301 |
* monitoring methods are either computed on demand, or are kept |
302 |
* in fields that are only updated when threads are otherwise |
303 |
* idle. |
304 |
* |
305 |
* Beware that there is a lot of representation-level coupling |
306 |
* among classes ForkJoinPool, ForkJoinWorkerThread, and |
307 |
* ForkJoinTask. For example, direct access to "workers" array by |
308 |
* workers, and direct access to ForkJoinTask.status by both |
309 |
* ForkJoinPool and ForkJoinWorkerThread. There is little point |
310 |
* trying to reduce this, since any associated future changes in |
311 |
* representations will need to be accompanied by algorithmic |
312 |
* changes anyway. |
313 |
* |
314 |
* Style notes: There are lots of inline assignments (of form |
315 |
* "while ((local = field) != 0)") which are usually the simplest |
316 |
* way to ensure read orderings. Also several occurrences of the |
317 |
* unusual "do {} while(!cas...)" which is the simplest way to |
318 |
* force an update of a CAS'ed variable. There are also a few |
319 |
* other coding oddities that help some methods perform reasonably |
320 |
* even when interpreted (not compiled). |
321 |
* |
322 |
* The order of declarations in this file is: (1) statics (2) |
323 |
* fields (along with constants used when unpacking some of them) |
324 |
* (3) internal control methods (4) callbacks and other support |
325 |
* for ForkJoinTask and ForkJoinWorkerThread classes, (5) exported |
326 |
* methods (plus a few little helpers). |
327 |
*/ |
328 |
|
329 |
/** |
330 |
* Factory for creating new {@link ForkJoinWorkerThread}s. |
331 |
* A {@code ForkJoinWorkerThreadFactory} must be defined and used |
332 |
* for {@code ForkJoinWorkerThread} subclasses that extend base |
333 |
* functionality or initialize threads with different contexts. |
334 |
*/ |
335 |
public static interface ForkJoinWorkerThreadFactory { |
336 |
/** |
337 |
* Returns a new worker thread operating in the given pool. |
338 |
* |
339 |
* @param pool the pool this thread works in |
340 |
* @throws NullPointerException if the pool is null |
341 |
*/ |
342 |
public ForkJoinWorkerThread newThread(ForkJoinPool pool); |
343 |
} |
344 |
|
345 |
/** |
346 |
* Default ForkJoinWorkerThreadFactory implementation; creates a |
347 |
* new ForkJoinWorkerThread. |
348 |
*/ |
349 |
static class DefaultForkJoinWorkerThreadFactory |
350 |
implements ForkJoinWorkerThreadFactory { |
351 |
public ForkJoinWorkerThread newThread(ForkJoinPool pool) { |
352 |
return new ForkJoinWorkerThread(pool); |
353 |
} |
354 |
} |
355 |
|
356 |
/** |
357 |
* Creates a new ForkJoinWorkerThread. This factory is used unless |
358 |
* overridden in ForkJoinPool constructors. |
359 |
*/ |
360 |
public static final ForkJoinWorkerThreadFactory |
361 |
defaultForkJoinWorkerThreadFactory = |
362 |
new DefaultForkJoinWorkerThreadFactory(); |
363 |
|
364 |
/** |
365 |
* Permission required for callers of methods that may start or |
366 |
* kill threads. |
367 |
*/ |
368 |
private static final RuntimePermission modifyThreadPermission = |
369 |
new RuntimePermission("modifyThread"); |
370 |
|
371 |
/** |
372 |
* If there is a security manager, makes sure caller has |
373 |
* permission to modify threads. |
374 |
*/ |
375 |
private static void checkPermission() { |
376 |
SecurityManager security = System.getSecurityManager(); |
377 |
if (security != null) |
378 |
security.checkPermission(modifyThreadPermission); |
379 |
} |
380 |
|
381 |
/** |
382 |
* Generator for assigning sequence numbers as pool names. |
383 |
*/ |
384 |
private static final AtomicInteger poolNumberGenerator = |
385 |
new AtomicInteger(); |
386 |
|
387 |
/** |
388 |
* Absolute bound for parallelism level. Twice this number must |
389 |
* fit into a 16bit field to enable word-packing for some counts. |
390 |
*/ |
391 |
private static final int MAX_THREADS = 0x7fff; |
392 |
|
393 |
/** |
394 |
* Array holding all worker threads in the pool. Array size must |
395 |
* be a power of two. Updates and replacements are protected by |
396 |
* workerLock, but the array is always kept in a consistent enough |
397 |
* state to be randomly accessed without locking by workers |
398 |
* performing work-stealing, as well as other traversal-based |
399 |
* methods in this class. All readers must tolerate that some |
400 |
* array slots may be null. |
401 |
*/ |
402 |
volatile ForkJoinWorkerThread[] workers; |
403 |
|
404 |
/** |
405 |
* Queue for external submissions. |
406 |
*/ |
407 |
private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue; |
408 |
|
409 |
/** |
410 |
* Lock protecting updates to workers array. |
411 |
*/ |
412 |
private final ReentrantLock workerLock; |
413 |
|
414 |
/** |
415 |
* Latch released upon termination. |
416 |
*/ |
417 |
private final CountDownLatch terminationLatch; |
418 |
|
419 |
/** |
420 |
* Creation factory for worker threads. |
421 |
*/ |
422 |
private final ForkJoinWorkerThreadFactory factory; |
423 |
|
424 |
/** |
425 |
* Sum of per-thread steal counts, updated only when threads are |
426 |
* idle or terminating. |
427 |
*/ |
428 |
private volatile long stealCount; |
429 |
|
430 |
/** |
431 |
* Encoded record of top of treiber stack of threads waiting for |
432 |
* events. The top 32 bits contain the count being waited for. The |
433 |
* bottom word contains one plus the pool index of waiting worker |
434 |
* thread. |
435 |
*/ |
436 |
private volatile long eventWaiters; |
437 |
|
438 |
private static final int EVENT_COUNT_SHIFT = 32; |
439 |
private static final long WAITER_INDEX_MASK = (1L << EVENT_COUNT_SHIFT)-1L; |
440 |
|
441 |
/** |
442 |
* A counter for events that may wake up worker threads: |
443 |
* - Submission of a new task to the pool |
444 |
* - A worker pushing a task on an empty queue |
445 |
* - termination and reconfiguration |
446 |
*/ |
447 |
private volatile int eventCount; |
448 |
|
449 |
/** |
450 |
* Lifecycle control. The low word contains the number of workers |
451 |
* that are (probably) executing tasks. This value is atomically |
452 |
* incremented before a worker gets a task to run, and decremented |
453 |
* when worker has no tasks and cannot find any. Bits 16-18 |
454 |
* contain runLevel value. When all are zero, the pool is |
455 |
* running. Level transitions are monotonic (running -> shutdown |
456 |
* -> terminating -> terminated) so each transition adds a bit. |
457 |
* These are bundled together to ensure consistent read for |
458 |
* termination checks (i.e., that runLevel is at least SHUTDOWN |
459 |
* and active threads is zero). |
460 |
*/ |
461 |
private volatile int runState; |
462 |
|
463 |
// Note: The order among run level values matters. |
464 |
private static final int RUNLEVEL_SHIFT = 16; |
465 |
private static final int SHUTDOWN = 1 << RUNLEVEL_SHIFT; |
466 |
private static final int TERMINATING = 1 << (RUNLEVEL_SHIFT + 1); |
467 |
private static final int TERMINATED = 1 << (RUNLEVEL_SHIFT + 2); |
468 |
private static final int ACTIVE_COUNT_MASK = (1 << RUNLEVEL_SHIFT) - 1; |
469 |
private static final int ONE_ACTIVE = 1; // active update delta |
470 |
|
471 |
/** |
472 |
* Holds number of total (i.e., created and not yet terminated) |
473 |
* and running (i.e., not blocked on joins or other managed sync) |
474 |
* threads, packed together to ensure consistent snapshot when |
475 |
* making decisions about creating and suspending spare |
476 |
* threads. Updated only by CAS. Note that adding a new worker |
477 |
* requires incrementing both counts, since workers start off in |
478 |
* running state. This field is also used for memory-fencing |
479 |
* configuration parameters. |
480 |
*/ |
481 |
private volatile int workerCounts; |
482 |
|
483 |
private static final int TOTAL_COUNT_SHIFT = 16; |
484 |
private static final int RUNNING_COUNT_MASK = (1 << TOTAL_COUNT_SHIFT) - 1; |
485 |
private static final int ONE_RUNNING = 1; |
486 |
private static final int ONE_TOTAL = 1 << TOTAL_COUNT_SHIFT; |
487 |
|
488 |
/* |
489 |
* Fields parallelism. maxPoolSize, and maintainsParallelism are |
490 |
* non-volatile, but external reads/writes use workerCount fences |
491 |
* to ensure visability. |
492 |
*/ |
493 |
|
494 |
/** |
495 |
* The target parallelism level. |
496 |
*/ |
497 |
private int parallelism; |
498 |
|
499 |
/** |
500 |
* The maximum allowed pool size. |
501 |
*/ |
502 |
private int maxPoolSize; |
503 |
|
504 |
/** |
505 |
* True if use local fifo, not default lifo, for local polling |
506 |
* Replicated by ForkJoinWorkerThreads |
507 |
*/ |
508 |
private volatile boolean locallyFifo; |
509 |
|
510 |
/** |
511 |
* Controls whether to add spares to maintain parallelism |
512 |
*/ |
513 |
private boolean maintainsParallelism; |
514 |
|
515 |
/** |
516 |
* The uncaught exception handler used when any worker |
517 |
* abruptly terminates |
518 |
*/ |
519 |
private volatile Thread.UncaughtExceptionHandler ueh; |
520 |
|
521 |
/** |
522 |
* Pool number, just for assigning useful names to worker threads |
523 |
*/ |
524 |
private final int poolNumber; |
525 |
|
526 |
// utilities for updating fields |
527 |
|
528 |
/** |
529 |
* Adds delta to running count. Used mainly by ForkJoinTask. |
530 |
*/ |
531 |
final void updateRunningCount(int delta) { |
532 |
int wc; |
533 |
do {} while (!UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
534 |
wc = workerCounts, |
535 |
wc + delta)); |
536 |
} |
537 |
|
538 |
/** |
539 |
* Decrements running count unless already zero |
540 |
*/ |
541 |
final boolean tryDecrementRunningCount() { |
542 |
int wc = workerCounts; |
543 |
if ((wc & RUNNING_COUNT_MASK) == 0) |
544 |
return false; |
545 |
return UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
546 |
wc, wc - ONE_RUNNING); |
547 |
} |
548 |
|
549 |
/** |
550 |
* Write fence for user modifications of pool parameters |
551 |
* (parallelism. etc). Note that it doesn't matter if CAS fails. |
552 |
*/ |
553 |
private void workerCountWriteFence() { |
554 |
int wc; |
555 |
UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
556 |
wc = workerCounts, wc); |
557 |
} |
558 |
|
559 |
/** |
560 |
* Read fence for external reads of pool parameters |
561 |
* (parallelism. maxPoolSize, etc). |
562 |
*/ |
563 |
private void workerCountReadFence() { |
564 |
int ignore = workerCounts; |
565 |
} |
566 |
|
567 |
/** |
568 |
* Tries incrementing active count; fails on contention. |
569 |
* Called by workers before executing tasks. |
570 |
* |
571 |
* @return true on success |
572 |
*/ |
573 |
final boolean tryIncrementActiveCount() { |
574 |
int c; |
575 |
return UNSAFE.compareAndSwapInt(this, runStateOffset, |
576 |
c = runState, c + ONE_ACTIVE); |
577 |
} |
578 |
|
579 |
/** |
580 |
* Tries decrementing active count; fails on contention. |
581 |
* Called when workers cannot find tasks to run. |
582 |
*/ |
583 |
final boolean tryDecrementActiveCount() { |
584 |
int c; |
585 |
return UNSAFE.compareAndSwapInt(this, runStateOffset, |
586 |
c = runState, c - ONE_ACTIVE); |
587 |
} |
588 |
|
589 |
/** |
590 |
* Advances to at least the given level. Returns true if not |
591 |
* already in at least the given level. |
592 |
*/ |
593 |
private boolean advanceRunLevel(int level) { |
594 |
for (;;) { |
595 |
int s = runState; |
596 |
if ((s & level) != 0) |
597 |
return false; |
598 |
if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, s | level)) |
599 |
return true; |
600 |
} |
601 |
} |
602 |
|
603 |
// workers array maintenance |
604 |
|
605 |
/** |
606 |
* Records and returns a workers array index for new worker. |
607 |
*/ |
608 |
private int recordWorker(ForkJoinWorkerThread w) { |
609 |
// Try using slot totalCount-1. If not available, scan and/or resize |
610 |
int k = (workerCounts >>> TOTAL_COUNT_SHIFT) - 1; |
611 |
final ReentrantLock lock = this.workerLock; |
612 |
lock.lock(); |
613 |
try { |
614 |
ForkJoinWorkerThread[] ws = workers; |
615 |
int nws = ws.length; |
616 |
if (k < 0 || k >= nws || ws[k] != null) { |
617 |
for (k = 0; k < nws && ws[k] != null; ++k) |
618 |
; |
619 |
if (k == nws) |
620 |
ws = Arrays.copyOf(ws, nws << 1); |
621 |
} |
622 |
ws[k] = w; |
623 |
workers = ws; // volatile array write ensures slot visibility |
624 |
} finally { |
625 |
lock.unlock(); |
626 |
} |
627 |
return k; |
628 |
} |
629 |
|
630 |
/** |
631 |
* Nulls out record of worker in workers array |
632 |
*/ |
633 |
private void forgetWorker(ForkJoinWorkerThread w) { |
634 |
int idx = w.poolIndex; |
635 |
// Locking helps method recordWorker avoid unecessary expansion |
636 |
final ReentrantLock lock = this.workerLock; |
637 |
lock.lock(); |
638 |
try { |
639 |
ForkJoinWorkerThread[] ws = workers; |
640 |
if (idx >= 0 && idx < ws.length && ws[idx] == w) // verify |
641 |
ws[idx] = null; |
642 |
} finally { |
643 |
lock.unlock(); |
644 |
} |
645 |
} |
646 |
|
647 |
// adding and removing workers |
648 |
|
649 |
/** |
650 |
* Tries to create and add new worker. Assumes that worker counts |
651 |
* are already updated to accommodate the worker, so adjusts on |
652 |
* failure. |
653 |
* |
654 |
* @return new worker or null if creation failed |
655 |
*/ |
656 |
private ForkJoinWorkerThread addWorker() { |
657 |
ForkJoinWorkerThread w = null; |
658 |
try { |
659 |
w = factory.newThread(this); |
660 |
} finally { // Adjust on either null or exceptional factory return |
661 |
if (w == null) { |
662 |
onWorkerCreationFailure(); |
663 |
return null; |
664 |
} |
665 |
} |
666 |
w.start(recordWorker(w), locallyFifo, ueh); |
667 |
return w; |
668 |
} |
669 |
|
670 |
/** |
671 |
* Adjusts counts upon failure to create worker |
672 |
*/ |
673 |
private void onWorkerCreationFailure() { |
674 |
for (;;) { |
675 |
int wc = workerCounts; |
676 |
if ((wc >>> TOTAL_COUNT_SHIFT) > 0 && |
677 |
UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
678 |
wc, wc - (ONE_RUNNING|ONE_TOTAL))) |
679 |
break; |
680 |
} |
681 |
tryTerminate(false); // in case of failure during shutdown |
682 |
} |
683 |
|
684 |
/** |
685 |
* Create enough total workers to establish target parallelism, |
686 |
* giving up if terminating or addWorker fails |
687 |
*/ |
688 |
private void ensureEnoughTotalWorkers() { |
689 |
int wc; |
690 |
while (((wc = workerCounts) >>> TOTAL_COUNT_SHIFT) < parallelism && |
691 |
runState < TERMINATING) { |
692 |
if ((UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
693 |
wc, wc + (ONE_RUNNING|ONE_TOTAL)) && |
694 |
addWorker() == null)) |
695 |
break; |
696 |
} |
697 |
} |
698 |
|
699 |
/** |
700 |
* Final callback from terminating worker. Removes record of |
701 |
* worker from array, and adjusts counts. If pool is shutting |
702 |
* down, tries to complete terminatation, else possibly replaces |
703 |
* the worker. |
704 |
* |
705 |
* @param w the worker |
706 |
*/ |
707 |
final void workerTerminated(ForkJoinWorkerThread w) { |
708 |
if (w.active) { // force inactive |
709 |
w.active = false; |
710 |
do {} while (!tryDecrementActiveCount()); |
711 |
} |
712 |
forgetWorker(w); |
713 |
|
714 |
// Decrement total count, and if was running, running count |
715 |
// Spin (waiting for other updates) if either would be negative |
716 |
int nr = w.isTrimmed() ? 0 : ONE_RUNNING; |
717 |
int unit = ONE_TOTAL + nr; |
718 |
for (;;) { |
719 |
int wc = workerCounts; |
720 |
int rc = wc & RUNNING_COUNT_MASK; |
721 |
if (rc - nr < 0 || (wc >>> TOTAL_COUNT_SHIFT) == 0) |
722 |
Thread.yield(); // back off if waiting for other updates |
723 |
else if (UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
724 |
wc, wc - unit)) |
725 |
break; |
726 |
} |
727 |
|
728 |
accumulateStealCount(w); // collect final count |
729 |
if (!tryTerminate(false)) |
730 |
ensureEnoughTotalWorkers(); |
731 |
} |
732 |
|
733 |
// Waiting for and signalling events |
734 |
|
735 |
/** |
736 |
* Ensures eventCount on exit is different (mod 2^32) than on |
737 |
* entry. CAS failures are OK -- any change in count suffices. |
738 |
*/ |
739 |
private void advanceEventCount() { |
740 |
int c; |
741 |
UNSAFE.compareAndSwapInt(this, eventCountOffset, c = eventCount, c+1); |
742 |
} |
743 |
|
744 |
/** |
745 |
* Releases workers blocked on a count not equal to current count. |
746 |
*/ |
747 |
final void releaseWaiters() { |
748 |
long top; |
749 |
int id; |
750 |
while ((id = (int)((top = eventWaiters) & WAITER_INDEX_MASK)) > 0 && |
751 |
(int)(top >>> EVENT_COUNT_SHIFT) != eventCount) { |
752 |
ForkJoinWorkerThread[] ws = workers; |
753 |
ForkJoinWorkerThread w; |
754 |
if (ws.length >= id && (w = ws[id - 1]) != null && |
755 |
UNSAFE.compareAndSwapLong(this, eventWaitersOffset, |
756 |
top, w.nextWaiter)) |
757 |
LockSupport.unpark(w); |
758 |
} |
759 |
} |
760 |
|
761 |
/** |
762 |
* Advances eventCount and releases waiters until interference by |
763 |
* other releasing threads is detected. |
764 |
*/ |
765 |
final void signalWork() { |
766 |
int ec; |
767 |
UNSAFE.compareAndSwapInt(this, eventCountOffset, ec=eventCount, ec+1); |
768 |
outer:for (;;) { |
769 |
long top = eventWaiters; |
770 |
ec = eventCount; |
771 |
for (;;) { |
772 |
ForkJoinWorkerThread[] ws; ForkJoinWorkerThread w; |
773 |
int id = (int)(top & WAITER_INDEX_MASK); |
774 |
if (id <= 0 || (int)(top >>> EVENT_COUNT_SHIFT) == ec) |
775 |
return; |
776 |
if ((ws = workers).length < id || (w = ws[id - 1]) == null || |
777 |
!UNSAFE.compareAndSwapLong(this, eventWaitersOffset, |
778 |
top, top = w.nextWaiter)) |
779 |
continue outer; // possibly stale; reread |
780 |
LockSupport.unpark(w); |
781 |
if (top != eventWaiters) // let someone else take over |
782 |
return; |
783 |
} |
784 |
} |
785 |
} |
786 |
|
787 |
/** |
788 |
* If worker is inactive, blocks until terminating or event count |
789 |
* advances from last value held by worker; in any case helps |
790 |
* release others. |
791 |
* |
792 |
* @param w the calling worker thread |
793 |
*/ |
794 |
private void eventSync(ForkJoinWorkerThread w) { |
795 |
if (!w.active) { |
796 |
int prev = w.lastEventCount; |
797 |
long nextTop = (((long)prev << EVENT_COUNT_SHIFT) | |
798 |
((long)(w.poolIndex + 1))); |
799 |
long top; |
800 |
while ((runState < SHUTDOWN || !tryTerminate(false)) && |
801 |
(((int)(top = eventWaiters) & WAITER_INDEX_MASK) == 0 || |
802 |
(int)(top >>> EVENT_COUNT_SHIFT) == prev) && |
803 |
eventCount == prev) { |
804 |
if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset, |
805 |
w.nextWaiter = top, nextTop)) { |
806 |
accumulateStealCount(w); // transfer steals while idle |
807 |
Thread.interrupted(); // clear/ignore interrupt |
808 |
while (eventCount == prev) |
809 |
w.doPark(); |
810 |
break; |
811 |
} |
812 |
} |
813 |
w.lastEventCount = eventCount; |
814 |
} |
815 |
releaseWaiters(); |
816 |
} |
817 |
|
818 |
/** |
819 |
* Callback from workers invoked upon each top-level action (i.e., |
820 |
* stealing a task or taking a submission and running |
821 |
* it). Performs one or both of the following: |
822 |
* |
823 |
* * If the worker cannot find work, updates its active status to |
824 |
* inactive and updates activeCount unless there is contention, in |
825 |
* which case it may try again (either in this or a subsequent |
826 |
* call). Additionally, awaits the next task event and/or helps |
827 |
* wake up other releasable waiters. |
828 |
* |
829 |
* * If there are too many running threads, suspends this worker |
830 |
* (first forcing inactivation if necessary). If it is not |
831 |
* resumed before a keepAlive elapses, the worker may be "trimmed" |
832 |
* -- killed while suspended within suspendAsSpare. Otherwise, |
833 |
* upon resume it rechecks to make sure that it is still needed. |
834 |
* |
835 |
* @param w the worker |
836 |
* @param worked false if the worker scanned for work but didn't |
837 |
* find any (in which case it may block waiting for work). |
838 |
*/ |
839 |
final void preStep(ForkJoinWorkerThread w, boolean worked) { |
840 |
boolean active = w.active; |
841 |
boolean inactivate = !worked & active; |
842 |
for (;;) { |
843 |
if (inactivate) { |
844 |
int c = runState; |
845 |
if (UNSAFE.compareAndSwapInt(this, runStateOffset, |
846 |
c, c - ONE_ACTIVE)) |
847 |
inactivate = active = w.active = false; |
848 |
} |
849 |
int wc = workerCounts; |
850 |
if ((wc & RUNNING_COUNT_MASK) <= parallelism) { |
851 |
if (!worked) |
852 |
eventSync(w); |
853 |
return; |
854 |
} |
855 |
if (!(inactivate |= active) && // must inactivate to suspend |
856 |
UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
857 |
wc, wc - ONE_RUNNING) && |
858 |
!w.suspendAsSpare()) // false if trimmed |
859 |
return; |
860 |
} |
861 |
} |
862 |
|
863 |
/** |
864 |
* Adjusts counts and creates or resumes compensating threads for |
865 |
* a worker blocking on task joinMe. First tries resuming an |
866 |
* existing spare (which usually also avoids any count |
867 |
* adjustment), but must then decrement running count to determine |
868 |
* whether a new thread is needed. See above for fuller |
869 |
* explanation. This code is sprawled out non-modularly mainly |
870 |
* because adaptive spinning works best if the entire method is |
871 |
* either interpreted or compiled vs having only some pieces of it |
872 |
* compiled. |
873 |
* |
874 |
* @param joinMe the task to join |
875 |
* @return task status on exit (to simplify usage by callers) |
876 |
*/ |
877 |
final int awaitJoin(ForkJoinTask<?> joinMe) { |
878 |
int pc = parallelism; |
879 |
boolean adj = false; // true when running count adjusted |
880 |
int scans = 0; |
881 |
|
882 |
while (joinMe.status >= 0) { |
883 |
ForkJoinWorkerThread spare = null; |
884 |
if ((workerCounts & RUNNING_COUNT_MASK) < pc) { |
885 |
ForkJoinWorkerThread[] ws = workers; |
886 |
int nws = ws.length; |
887 |
for (int i = 0; i < nws; ++i) { |
888 |
ForkJoinWorkerThread w = ws[i]; |
889 |
if (w != null && w.isSuspended()) { |
890 |
spare = w; |
891 |
break; |
892 |
} |
893 |
} |
894 |
if (joinMe.status < 0) |
895 |
break; |
896 |
} |
897 |
int wc = workerCounts; |
898 |
int rc = wc & RUNNING_COUNT_MASK; |
899 |
int dc = pc - rc; |
900 |
if (dc > 0 && spare != null && spare.tryUnsuspend()) { |
901 |
if (adj) { |
902 |
int c; |
903 |
do {} while (!UNSAFE.compareAndSwapInt |
904 |
(this, workerCountsOffset, |
905 |
c = workerCounts, c + ONE_RUNNING)); |
906 |
} |
907 |
adj = true; |
908 |
LockSupport.unpark(spare); |
909 |
} |
910 |
else if (adj) { |
911 |
if (dc <= 0) |
912 |
break; |
913 |
int tc = wc >>> TOTAL_COUNT_SHIFT; |
914 |
if (scans > tc) { |
915 |
int ts = (tc - pc) * pc; |
916 |
if (rc != 0 && (dc * dc < ts || !maintainsParallelism)) |
917 |
break; |
918 |
if (scans > ts && tc < maxPoolSize && |
919 |
UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc, |
920 |
wc+(ONE_RUNNING|ONE_TOTAL))){ |
921 |
addWorker(); |
922 |
break; |
923 |
} |
924 |
} |
925 |
} |
926 |
else if (rc != 0) |
927 |
adj = UNSAFE.compareAndSwapInt (this, workerCountsOffset, |
928 |
wc, wc - ONE_RUNNING); |
929 |
if ((scans++ & 1) == 0) |
930 |
releaseWaiters(); // help others progress |
931 |
else |
932 |
Thread.yield(); // avoid starving productive threads |
933 |
} |
934 |
|
935 |
if (adj) { |
936 |
joinMe.internalAwaitDone(); |
937 |
int c; |
938 |
do {} while (!UNSAFE.compareAndSwapInt |
939 |
(this, workerCountsOffset, |
940 |
c = workerCounts, c + ONE_RUNNING)); |
941 |
} |
942 |
return joinMe.status; |
943 |
} |
944 |
|
945 |
/** |
946 |
* Same idea as awaitJoin |
947 |
*/ |
948 |
final void awaitBlocker(ManagedBlocker blocker, boolean maintainPar) |
949 |
throws InterruptedException { |
950 |
maintainPar &= maintainsParallelism; |
951 |
int pc = parallelism; |
952 |
boolean adj = false; // true when running count adjusted |
953 |
int scans = 0; |
954 |
boolean done; |
955 |
|
956 |
for (;;) { |
957 |
if (done = blocker.isReleasable()) |
958 |
break; |
959 |
ForkJoinWorkerThread spare = null; |
960 |
if ((workerCounts & RUNNING_COUNT_MASK) < pc) { |
961 |
ForkJoinWorkerThread[] ws = workers; |
962 |
int nws = ws.length; |
963 |
for (int i = 0; i < nws; ++i) { |
964 |
ForkJoinWorkerThread w = ws[i]; |
965 |
if (w != null && w.isSuspended()) { |
966 |
spare = w; |
967 |
break; |
968 |
} |
969 |
} |
970 |
if (done = blocker.isReleasable()) |
971 |
break; |
972 |
} |
973 |
int wc = workerCounts; |
974 |
int rc = wc & RUNNING_COUNT_MASK; |
975 |
int dc = pc - rc; |
976 |
if (dc > 0 && spare != null && spare.tryUnsuspend()) { |
977 |
if (adj) { |
978 |
int c; |
979 |
do {} while (!UNSAFE.compareAndSwapInt |
980 |
(this, workerCountsOffset, |
981 |
c = workerCounts, c + ONE_RUNNING)); |
982 |
} |
983 |
adj = true; |
984 |
LockSupport.unpark(spare); |
985 |
} |
986 |
else if (adj) { |
987 |
if (dc <= 0) |
988 |
break; |
989 |
int tc = wc >>> TOTAL_COUNT_SHIFT; |
990 |
if (scans > tc) { |
991 |
int ts = (tc - pc) * pc; |
992 |
if (rc != 0 && (dc * dc < ts || !maintainPar)) |
993 |
break; |
994 |
if (scans > ts && tc < maxPoolSize && |
995 |
UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc, |
996 |
wc+(ONE_RUNNING|ONE_TOTAL))){ |
997 |
addWorker(); |
998 |
break; |
999 |
} |
1000 |
} |
1001 |
} |
1002 |
else if (rc != 0) |
1003 |
adj = UNSAFE.compareAndSwapInt (this, workerCountsOffset, |
1004 |
wc, wc - ONE_RUNNING); |
1005 |
if ((++scans & 1) == 0) |
1006 |
releaseWaiters(); // help others progress |
1007 |
else |
1008 |
Thread.yield(); // avoid starving productive threads |
1009 |
} |
1010 |
|
1011 |
try { |
1012 |
if (!done) |
1013 |
do {} while (!blocker.isReleasable() && !blocker.block()); |
1014 |
} finally { |
1015 |
if (adj) { |
1016 |
int c; |
1017 |
do {} while (!UNSAFE.compareAndSwapInt |
1018 |
(this, workerCountsOffset, |
1019 |
c = workerCounts, c + ONE_RUNNING)); |
1020 |
} |
1021 |
} |
1022 |
} |
1023 |
|
1024 |
/** |
1025 |
* Unless there are not enough other running threads, adjusts |
1026 |
* counts and blocks a worker performing helpJoin that cannot find |
1027 |
* any work. |
1028 |
* |
1029 |
* @return true if joinMe now done |
1030 |
*/ |
1031 |
final boolean tryAwaitBusyJoin(ForkJoinTask<?> joinMe) { |
1032 |
int pc = parallelism; |
1033 |
outer:for (;;) { |
1034 |
releaseWaiters(); |
1035 |
if ((workerCounts & RUNNING_COUNT_MASK) < pc) { |
1036 |
ForkJoinWorkerThread[] ws = workers; |
1037 |
int nws = ws.length; |
1038 |
for (int i = 0; i < nws; ++i) { |
1039 |
ForkJoinWorkerThread w = ws[i]; |
1040 |
if (w != null && w.isSuspended()) { |
1041 |
if (joinMe.status < 0) |
1042 |
return true; |
1043 |
if ((workerCounts & RUNNING_COUNT_MASK) > pc) |
1044 |
break; |
1045 |
if (w.tryUnsuspend()) { |
1046 |
LockSupport.unpark(w); |
1047 |
break outer; |
1048 |
} |
1049 |
continue outer; |
1050 |
} |
1051 |
} |
1052 |
} |
1053 |
if (joinMe.status < 0) |
1054 |
return true; |
1055 |
int wc = workerCounts; |
1056 |
if ((wc & RUNNING_COUNT_MASK) <= 2 || |
1057 |
(wc >>> TOTAL_COUNT_SHIFT) < pc) |
1058 |
return false; // keep this thread alive |
1059 |
if (UNSAFE.compareAndSwapInt(this, workerCountsOffset, |
1060 |
wc, wc - ONE_RUNNING)) |
1061 |
break; |
1062 |
} |
1063 |
|
1064 |
joinMe.internalAwaitDone(); |
1065 |
int c; |
1066 |
do {} while (!UNSAFE.compareAndSwapInt |
1067 |
(this, workerCountsOffset, |
1068 |
c = workerCounts, c + ONE_RUNNING)); |
1069 |
return true; |
1070 |
} |
1071 |
|
1072 |
/** |
1073 |
* Possibly initiates and/or completes termination. |
1074 |
* |
1075 |
* @param now if true, unconditionally terminate, else only |
1076 |
* if shutdown and empty queue and no active workers |
1077 |
* @return true if now terminating or terminated |
1078 |
*/ |
1079 |
private boolean tryTerminate(boolean now) { |
1080 |
if (now) |
1081 |
advanceRunLevel(SHUTDOWN); // ensure at least SHUTDOWN |
1082 |
else if (runState < SHUTDOWN || |
1083 |
!submissionQueue.isEmpty() || |
1084 |
(runState & ACTIVE_COUNT_MASK) != 0) |
1085 |
return false; |
1086 |
|
1087 |
if (advanceRunLevel(TERMINATING)) |
1088 |
startTerminating(); |
1089 |
|
1090 |
// Finish now if all threads terminated; else in some subsequent call |
1091 |
if ((workerCounts >>> TOTAL_COUNT_SHIFT) == 0) { |
1092 |
advanceRunLevel(TERMINATED); |
1093 |
terminationLatch.countDown(); |
1094 |
} |
1095 |
return true; |
1096 |
} |
1097 |
|
1098 |
/** |
1099 |
* Actions on transition to TERMINATING |
1100 |
*/ |
1101 |
private void startTerminating() { |
1102 |
for (int i = 0; i < 2; ++i) { // twice to mop up newly created workers |
1103 |
cancelSubmissions(); |
1104 |
shutdownWorkers(); |
1105 |
cancelWorkerTasks(); |
1106 |
advanceEventCount(); |
1107 |
releaseWaiters(); |
1108 |
interruptWorkers(); |
1109 |
} |
1110 |
} |
1111 |
|
1112 |
/** |
1113 |
* Clear out and cancel submissions, ignoring exceptions |
1114 |
*/ |
1115 |
private void cancelSubmissions() { |
1116 |
ForkJoinTask<?> task; |
1117 |
while ((task = submissionQueue.poll()) != null) { |
1118 |
try { |
1119 |
task.cancel(false); |
1120 |
} catch (Throwable ignore) { |
1121 |
} |
1122 |
} |
1123 |
} |
1124 |
|
1125 |
/** |
1126 |
* Sets all worker run states to at least shutdown, |
1127 |
* also resuming suspended workers |
1128 |
*/ |
1129 |
private void shutdownWorkers() { |
1130 |
ForkJoinWorkerThread[] ws = workers; |
1131 |
int nws = ws.length; |
1132 |
for (int i = 0; i < nws; ++i) { |
1133 |
ForkJoinWorkerThread w = ws[i]; |
1134 |
if (w != null) |
1135 |
w.shutdown(); |
1136 |
} |
1137 |
} |
1138 |
|
1139 |
/** |
1140 |
* Clears out and cancels all locally queued tasks |
1141 |
*/ |
1142 |
private void cancelWorkerTasks() { |
1143 |
ForkJoinWorkerThread[] ws = workers; |
1144 |
int nws = ws.length; |
1145 |
for (int i = 0; i < nws; ++i) { |
1146 |
ForkJoinWorkerThread w = ws[i]; |
1147 |
if (w != null) |
1148 |
w.cancelTasks(); |
1149 |
} |
1150 |
} |
1151 |
|
1152 |
/** |
1153 |
* Unsticks all workers blocked on joins etc |
1154 |
*/ |
1155 |
private void interruptWorkers() { |
1156 |
ForkJoinWorkerThread[] ws = workers; |
1157 |
int nws = ws.length; |
1158 |
for (int i = 0; i < nws; ++i) { |
1159 |
ForkJoinWorkerThread w = ws[i]; |
1160 |
if (w != null && !w.isTerminated()) { |
1161 |
try { |
1162 |
w.interrupt(); |
1163 |
} catch (SecurityException ignore) { |
1164 |
} |
1165 |
} |
1166 |
} |
1167 |
} |
1168 |
|
1169 |
// misc support for ForkJoinWorkerThread |
1170 |
|
1171 |
/** |
1172 |
* Returns pool number |
1173 |
*/ |
1174 |
final int getPoolNumber() { |
1175 |
return poolNumber; |
1176 |
} |
1177 |
|
1178 |
/** |
1179 |
* Accumulates steal count from a worker, clearing |
1180 |
* the worker's value |
1181 |
*/ |
1182 |
final void accumulateStealCount(ForkJoinWorkerThread w) { |
1183 |
int sc = w.stealCount; |
1184 |
if (sc != 0) { |
1185 |
long c; |
1186 |
w.stealCount = 0; |
1187 |
do {} while (!UNSAFE.compareAndSwapLong(this, stealCountOffset, |
1188 |
c = stealCount, c + sc)); |
1189 |
} |
1190 |
} |
1191 |
|
1192 |
/** |
1193 |
* Returns the approximate (non-atomic) number of idle threads per |
1194 |
* active thread. |
1195 |
*/ |
1196 |
final int idlePerActive() { |
1197 |
int ac = runState; // no mask -- artifically boosts during shutdown |
1198 |
int pc = parallelism; // use targeted parallelism, not rc |
1199 |
// Use exact results for small values, saturate past 4 |
1200 |
return pc <= ac? 0 : pc >>> 1 <= ac? 1 : pc >>> 2 <= ac? 3 : pc >>> 3; |
1201 |
} |
1202 |
|
1203 |
// Public and protected methods |
1204 |
|
1205 |
// Constructors |
1206 |
|
1207 |
/** |
1208 |
* Creates a {@code ForkJoinPool} with parallelism equal to {@link |
1209 |
* java.lang.Runtime#availableProcessors}, and using the {@linkplain |
1210 |
* #defaultForkJoinWorkerThreadFactory default thread factory}. |
1211 |
* |
1212 |
* @throws SecurityException if a security manager exists and |
1213 |
* the caller is not permitted to modify threads |
1214 |
* because it does not hold {@link |
1215 |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
1216 |
*/ |
1217 |
public ForkJoinPool() { |
1218 |
this(Runtime.getRuntime().availableProcessors(), |
1219 |
defaultForkJoinWorkerThreadFactory); |
1220 |
} |
1221 |
|
1222 |
/** |
1223 |
* Creates a {@code ForkJoinPool} with the indicated parallelism |
1224 |
* level and using the {@linkplain |
1225 |
* #defaultForkJoinWorkerThreadFactory default thread factory}. |
1226 |
* |
1227 |
* @param parallelism the parallelism level |
1228 |
* @throws IllegalArgumentException if parallelism less than or |
1229 |
* equal to zero, or greater than implementation limit |
1230 |
* @throws SecurityException if a security manager exists and |
1231 |
* the caller is not permitted to modify threads |
1232 |
* because it does not hold {@link |
1233 |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
1234 |
*/ |
1235 |
public ForkJoinPool(int parallelism) { |
1236 |
this(parallelism, defaultForkJoinWorkerThreadFactory); |
1237 |
} |
1238 |
|
1239 |
/** |
1240 |
* Creates a {@code ForkJoinPool} with parallelism equal to {@link |
1241 |
* java.lang.Runtime#availableProcessors}, and using the given |
1242 |
* thread factory. |
1243 |
* |
1244 |
* @param factory the factory for creating new threads |
1245 |
* @throws NullPointerException if the factory is null |
1246 |
* @throws SecurityException if a security manager exists and |
1247 |
* the caller is not permitted to modify threads |
1248 |
* because it does not hold {@link |
1249 |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
1250 |
*/ |
1251 |
public ForkJoinPool(ForkJoinWorkerThreadFactory factory) { |
1252 |
this(Runtime.getRuntime().availableProcessors(), factory); |
1253 |
} |
1254 |
|
1255 |
/** |
1256 |
* Creates a {@code ForkJoinPool} with the given parallelism and |
1257 |
* thread factory. |
1258 |
* |
1259 |
* @param parallelism the parallelism level |
1260 |
* @param factory the factory for creating new threads |
1261 |
* @throws IllegalArgumentException if parallelism less than or |
1262 |
* equal to zero, or greater than implementation limit |
1263 |
* @throws NullPointerException if the factory is null |
1264 |
* @throws SecurityException if a security manager exists and |
1265 |
* the caller is not permitted to modify threads |
1266 |
* because it does not hold {@link |
1267 |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
1268 |
*/ |
1269 |
public ForkJoinPool(int parallelism, ForkJoinWorkerThreadFactory factory) { |
1270 |
checkPermission(); |
1271 |
if (factory == null) |
1272 |
throw new NullPointerException(); |
1273 |
if (parallelism <= 0 || parallelism > MAX_THREADS) |
1274 |
throw new IllegalArgumentException(); |
1275 |
this.poolNumber = poolNumberGenerator.incrementAndGet(); |
1276 |
int arraySize = initialArraySizeFor(parallelism); |
1277 |
this.parallelism = parallelism; |
1278 |
this.factory = factory; |
1279 |
this.maxPoolSize = MAX_THREADS; |
1280 |
this.maintainsParallelism = true; |
1281 |
this.workers = new ForkJoinWorkerThread[arraySize]; |
1282 |
this.submissionQueue = new LinkedTransferQueue<ForkJoinTask<?>>(); |
1283 |
this.workerLock = new ReentrantLock(); |
1284 |
this.terminationLatch = new CountDownLatch(1); |
1285 |
} |
1286 |
|
1287 |
/** |
1288 |
* Returns initial power of two size for workers array. |
1289 |
* @param pc the initial parallelism level |
1290 |
*/ |
1291 |
private static int initialArraySizeFor(int pc) { |
1292 |
// See Hackers Delight, sec 3.2. We know MAX_THREADS < (1 >>> 16) |
1293 |
int size = pc < MAX_THREADS ? pc + 1 : MAX_THREADS; |
1294 |
size |= size >>> 1; |
1295 |
size |= size >>> 2; |
1296 |
size |= size >>> 4; |
1297 |
size |= size >>> 8; |
1298 |
return size + 1; |
1299 |
} |
1300 |
|
1301 |
// Execution methods |
1302 |
|
1303 |
/** |
1304 |
* Common code for execute, invoke and submit |
1305 |
*/ |
1306 |
private <T> void doSubmit(ForkJoinTask<T> task) { |
1307 |
if (task == null) |
1308 |
throw new NullPointerException(); |
1309 |
if (runState >= SHUTDOWN) |
1310 |
throw new RejectedExecutionException(); |
1311 |
submissionQueue.offer(task); |
1312 |
advanceEventCount(); |
1313 |
releaseWaiters(); |
1314 |
ensureEnoughTotalWorkers(); |
1315 |
} |
1316 |
|
1317 |
/** |
1318 |
* Performs the given task, returning its result upon completion. |
1319 |
* |
1320 |
* @param task the task |
1321 |
* @return the task's result |
1322 |
* @throws NullPointerException if the task is null |
1323 |
* @throws RejectedExecutionException if the task cannot be |
1324 |
* scheduled for execution |
1325 |
*/ |
1326 |
public <T> T invoke(ForkJoinTask<T> task) { |
1327 |
doSubmit(task); |
1328 |
return task.join(); |
1329 |
} |
1330 |
|
1331 |
/** |
1332 |
* Arranges for (asynchronous) execution of the given task. |
1333 |
* |
1334 |
* @param task the task |
1335 |
* @throws NullPointerException if the task is null |
1336 |
* @throws RejectedExecutionException if the task cannot be |
1337 |
* scheduled for execution |
1338 |
*/ |
1339 |
public void execute(ForkJoinTask<?> task) { |
1340 |
doSubmit(task); |
1341 |
} |
1342 |
|
1343 |
// AbstractExecutorService methods |
1344 |
|
1345 |
/** |
1346 |
* @throws NullPointerException if the task is null |
1347 |
* @throws RejectedExecutionException if the task cannot be |
1348 |
* scheduled for execution |
1349 |
*/ |
1350 |
public void execute(Runnable task) { |
1351 |
ForkJoinTask<?> job; |
1352 |
if (task instanceof ForkJoinTask<?>) // avoid re-wrap |
1353 |
job = (ForkJoinTask<?>) task; |
1354 |
else |
1355 |
job = ForkJoinTask.adapt(task, null); |
1356 |
doSubmit(job); |
1357 |
} |
1358 |
|
1359 |
/** |
1360 |
* @throws NullPointerException if the task is null |
1361 |
* @throws RejectedExecutionException if the task cannot be |
1362 |
* scheduled for execution |
1363 |
*/ |
1364 |
public <T> ForkJoinTask<T> submit(Callable<T> task) { |
1365 |
ForkJoinTask<T> job = ForkJoinTask.adapt(task); |
1366 |
doSubmit(job); |
1367 |
return job; |
1368 |
} |
1369 |
|
1370 |
/** |
1371 |
* @throws NullPointerException if the task is null |
1372 |
* @throws RejectedExecutionException if the task cannot be |
1373 |
* scheduled for execution |
1374 |
*/ |
1375 |
public <T> ForkJoinTask<T> submit(Runnable task, T result) { |
1376 |
ForkJoinTask<T> job = ForkJoinTask.adapt(task, result); |
1377 |
doSubmit(job); |
1378 |
return job; |
1379 |
} |
1380 |
|
1381 |
/** |
1382 |
* @throws NullPointerException if the task is null |
1383 |
* @throws RejectedExecutionException if the task cannot be |
1384 |
* scheduled for execution |
1385 |
*/ |
1386 |
public ForkJoinTask<?> submit(Runnable task) { |
1387 |
ForkJoinTask<?> job; |
1388 |
if (task instanceof ForkJoinTask<?>) // avoid re-wrap |
1389 |
job = (ForkJoinTask<?>) task; |
1390 |
else |
1391 |
job = ForkJoinTask.adapt(task, null); |
1392 |
doSubmit(job); |
1393 |
return job; |
1394 |
} |
1395 |
|
1396 |
/** |
1397 |
* Submits a ForkJoinTask for execution. |
1398 |
* |
1399 |
* @param task the task to submit |
1400 |
* @return the task |
1401 |
* @throws NullPointerException if the task is null |
1402 |
* @throws RejectedExecutionException if the task cannot be |
1403 |
* scheduled for execution |
1404 |
*/ |
1405 |
public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) { |
1406 |
doSubmit(task); |
1407 |
return task; |
1408 |
} |
1409 |
|
1410 |
/** |
1411 |
* @throws NullPointerException {@inheritDoc} |
1412 |
* @throws RejectedExecutionException {@inheritDoc} |
1413 |
*/ |
1414 |
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) { |
1415 |
ArrayList<ForkJoinTask<T>> forkJoinTasks = |
1416 |
new ArrayList<ForkJoinTask<T>>(tasks.size()); |
1417 |
for (Callable<T> task : tasks) |
1418 |
forkJoinTasks.add(ForkJoinTask.adapt(task)); |
1419 |
invoke(new InvokeAll<T>(forkJoinTasks)); |
1420 |
|
1421 |
@SuppressWarnings({"unchecked", "rawtypes"}) |
1422 |
List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks; |
1423 |
return futures; |
1424 |
} |
1425 |
|
1426 |
static final class InvokeAll<T> extends RecursiveAction { |
1427 |
final ArrayList<ForkJoinTask<T>> tasks; |
1428 |
InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; } |
1429 |
public void compute() { |
1430 |
try { invokeAll(tasks); } |
1431 |
catch (Exception ignore) {} |
1432 |
} |
1433 |
private static final long serialVersionUID = -7914297376763021607L; |
1434 |
} |
1435 |
|
1436 |
/** |
1437 |
* Returns the factory used for constructing new workers. |
1438 |
* |
1439 |
* @return the factory used for constructing new workers |
1440 |
*/ |
1441 |
public ForkJoinWorkerThreadFactory getFactory() { |
1442 |
return factory; |
1443 |
} |
1444 |
|
1445 |
/** |
1446 |
* Returns the handler for internal worker threads that terminate |
1447 |
* due to unrecoverable errors encountered while executing tasks. |
1448 |
* |
1449 |
* @return the handler, or {@code null} if none |
1450 |
*/ |
1451 |
public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() { |
1452 |
workerCountReadFence(); |
1453 |
return ueh; |
1454 |
} |
1455 |
|
1456 |
/** |
1457 |
* Sets the handler for internal worker threads that terminate due |
1458 |
* to unrecoverable errors encountered while executing tasks. |
1459 |
* Unless set, the current default or ThreadGroup handler is used |
1460 |
* as handler. |
1461 |
* |
1462 |
* @param h the new handler |
1463 |
* @return the old handler, or {@code null} if none |
1464 |
* @throws SecurityException if a security manager exists and |
1465 |
* the caller is not permitted to modify threads |
1466 |
* because it does not hold {@link |
1467 |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
1468 |
*/ |
1469 |
public Thread.UncaughtExceptionHandler |
1470 |
setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h) { |
1471 |
checkPermission(); |
1472 |
Thread.UncaughtExceptionHandler old = ueh; |
1473 |
if (h != old) { |
1474 |
ueh = h; |
1475 |
ForkJoinWorkerThread[] ws = workers; |
1476 |
int nws = ws.length; |
1477 |
for (int i = 0; i < nws; ++i) { |
1478 |
ForkJoinWorkerThread w = ws[i]; |
1479 |
if (w != null) |
1480 |
w.setUncaughtExceptionHandler(h); |
1481 |
} |
1482 |
} |
1483 |
return old; |
1484 |
} |
1485 |
|
1486 |
/** |
1487 |
* Sets the target parallelism level of this pool. |
1488 |
* |
1489 |
* @param parallelism the target parallelism |
1490 |
* @throws IllegalArgumentException if parallelism less than or |
1491 |
* equal to zero or greater than maximum size bounds |
1492 |
* @throws SecurityException if a security manager exists and |
1493 |
* the caller is not permitted to modify threads |
1494 |
* because it does not hold {@link |
1495 |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
1496 |
*/ |
1497 |
public void setParallelism(int parallelism) { |
1498 |
checkPermission(); |
1499 |
if (parallelism <= 0 || parallelism > maxPoolSize) |
1500 |
throw new IllegalArgumentException(); |
1501 |
workerCountReadFence(); |
1502 |
int pc = this.parallelism; |
1503 |
if (pc != parallelism) { |
1504 |
this.parallelism = parallelism; |
1505 |
workerCountWriteFence(); |
1506 |
// Release spares. If too many, some will die after re-suspend |
1507 |
ForkJoinWorkerThread[] ws = workers; |
1508 |
int nws = ws.length; |
1509 |
for (int i = 0; i < nws; ++i) { |
1510 |
ForkJoinWorkerThread w = ws[i]; |
1511 |
if (w != null && w.tryUnsuspend()) { |
1512 |
int c; |
1513 |
do {} while (!UNSAFE.compareAndSwapInt |
1514 |
(this, workerCountsOffset, |
1515 |
c = workerCounts, c + ONE_RUNNING)); |
1516 |
LockSupport.unpark(w); |
1517 |
} |
1518 |
} |
1519 |
ensureEnoughTotalWorkers(); |
1520 |
advanceEventCount(); |
1521 |
releaseWaiters(); // force config recheck by existing workers |
1522 |
} |
1523 |
} |
1524 |
|
1525 |
/** |
1526 |
* Returns the targeted parallelism level of this pool. |
1527 |
* |
1528 |
* @return the targeted parallelism level of this pool |
1529 |
*/ |
1530 |
public int getParallelism() { |
1531 |
// workerCountReadFence(); // inlined below |
1532 |
int ignore = workerCounts; |
1533 |
return parallelism; |
1534 |
} |
1535 |
|
1536 |
/** |
1537 |
* Returns the number of worker threads that have started but not |
1538 |
* yet terminated. This result returned by this method may differ |
1539 |
* from {@link #getParallelism} when threads are created to |
1540 |
* maintain parallelism when others are cooperatively blocked. |
1541 |
* |
1542 |
* @return the number of worker threads |
1543 |
*/ |
1544 |
public int getPoolSize() { |
1545 |
return workerCounts >>> TOTAL_COUNT_SHIFT; |
1546 |
} |
1547 |
|
1548 |
/** |
1549 |
* Returns the maximum number of threads allowed to exist in the |
1550 |
* pool. Unless set using {@link #setMaximumPoolSize}, the |
1551 |
* maximum is an implementation-defined value designed only to |
1552 |
* prevent runaway growth. |
1553 |
* |
1554 |
* @return the maximum |
1555 |
*/ |
1556 |
public int getMaximumPoolSize() { |
1557 |
workerCountReadFence(); |
1558 |
return maxPoolSize; |
1559 |
} |
1560 |
|
1561 |
/** |
1562 |
* Sets the maximum number of threads allowed to exist in the |
1563 |
* pool. The given value should normally be greater than or equal |
1564 |
* to the {@link #getParallelism parallelism} level. Setting this |
1565 |
* value has no effect on current pool size. It controls |
1566 |
* construction of new threads. The use of this method may cause |
1567 |
* tasks that intrinsically require extra threads for dependent |
1568 |
* computations to indefinitely stall. If you are instead trying |
1569 |
* to minimize internal thread creation, consider setting {@link |
1570 |
* #setMaintainsParallelism} as false. |
1571 |
* |
1572 |
* @throws IllegalArgumentException if negative or greater than |
1573 |
* internal implementation limit |
1574 |
*/ |
1575 |
public void setMaximumPoolSize(int newMax) { |
1576 |
if (newMax < 0 || newMax > MAX_THREADS) |
1577 |
throw new IllegalArgumentException(); |
1578 |
maxPoolSize = newMax; |
1579 |
workerCountWriteFence(); |
1580 |
} |
1581 |
|
1582 |
/** |
1583 |
* Returns {@code true} if this pool dynamically maintains its |
1584 |
* target parallelism level. If false, new threads are added only |
1585 |
* to avoid possible starvation. This setting is by default true. |
1586 |
* |
1587 |
* @return {@code true} if maintains parallelism |
1588 |
*/ |
1589 |
public boolean getMaintainsParallelism() { |
1590 |
workerCountReadFence(); |
1591 |
return maintainsParallelism; |
1592 |
} |
1593 |
|
1594 |
/** |
1595 |
* Sets whether this pool dynamically maintains its target |
1596 |
* parallelism level. If false, new threads are added only to |
1597 |
* avoid possible starvation. |
1598 |
* |
1599 |
* @param enable {@code true} to maintain parallelism |
1600 |
*/ |
1601 |
public void setMaintainsParallelism(boolean enable) { |
1602 |
maintainsParallelism = enable; |
1603 |
workerCountWriteFence(); |
1604 |
} |
1605 |
|
1606 |
/** |
1607 |
* Establishes local first-in-first-out scheduling mode for forked |
1608 |
* tasks that are never joined. This mode may be more appropriate |
1609 |
* than default locally stack-based mode in applications in which |
1610 |
* worker threads only process asynchronous tasks. This method is |
1611 |
* designed to be invoked only when the pool is quiescent, and |
1612 |
* typically only before any tasks are submitted. The effects of |
1613 |
* invocations at other times may be unpredictable. |
1614 |
* |
1615 |
* @param async if {@code true}, use locally FIFO scheduling |
1616 |
* @return the previous mode |
1617 |
* @see #getAsyncMode |
1618 |
*/ |
1619 |
public boolean setAsyncMode(boolean async) { |
1620 |
workerCountReadFence(); |
1621 |
boolean oldMode = locallyFifo; |
1622 |
if (oldMode != async) { |
1623 |
locallyFifo = async; |
1624 |
workerCountWriteFence(); |
1625 |
ForkJoinWorkerThread[] ws = workers; |
1626 |
int nws = ws.length; |
1627 |
for (int i = 0; i < nws; ++i) { |
1628 |
ForkJoinWorkerThread w = ws[i]; |
1629 |
if (w != null) |
1630 |
w.setAsyncMode(async); |
1631 |
} |
1632 |
} |
1633 |
return oldMode; |
1634 |
} |
1635 |
|
1636 |
/** |
1637 |
* Returns {@code true} if this pool uses local first-in-first-out |
1638 |
* scheduling mode for forked tasks that are never joined. |
1639 |
* |
1640 |
* @return {@code true} if this pool uses async mode |
1641 |
* @see #setAsyncMode |
1642 |
*/ |
1643 |
public boolean getAsyncMode() { |
1644 |
workerCountReadFence(); |
1645 |
return locallyFifo; |
1646 |
} |
1647 |
|
1648 |
/** |
1649 |
* Returns an estimate of the number of worker threads that are |
1650 |
* not blocked waiting to join tasks or for other managed |
1651 |
* synchronization. This method may overestimate the |
1652 |
* number of running threads. |
1653 |
* |
1654 |
* @return the number of worker threads |
1655 |
*/ |
1656 |
public int getRunningThreadCount() { |
1657 |
return workerCounts & RUNNING_COUNT_MASK; |
1658 |
} |
1659 |
|
1660 |
/** |
1661 |
* Returns an estimate of the number of threads that are currently |
1662 |
* stealing or executing tasks. This method may overestimate the |
1663 |
* number of active threads. |
1664 |
* |
1665 |
* @return the number of active threads |
1666 |
*/ |
1667 |
public int getActiveThreadCount() { |
1668 |
return runState & ACTIVE_COUNT_MASK; |
1669 |
} |
1670 |
|
1671 |
/** |
1672 |
* Returns {@code true} if all worker threads are currently idle. |
1673 |
* An idle worker is one that cannot obtain a task to execute |
1674 |
* because none are available to steal from other threads, and |
1675 |
* there are no pending submissions to the pool. This method is |
1676 |
* conservative; it might not return {@code true} immediately upon |
1677 |
* idleness of all threads, but will eventually become true if |
1678 |
* threads remain inactive. |
1679 |
* |
1680 |
* @return {@code true} if all threads are currently idle |
1681 |
*/ |
1682 |
public boolean isQuiescent() { |
1683 |
return (runState & ACTIVE_COUNT_MASK) == 0; |
1684 |
} |
1685 |
|
1686 |
/** |
1687 |
* Returns an estimate of the total number of tasks stolen from |
1688 |
* one thread's work queue by another. The reported value |
1689 |
* underestimates the actual total number of steals when the pool |
1690 |
* is not quiescent. This value may be useful for monitoring and |
1691 |
* tuning fork/join programs: in general, steal counts should be |
1692 |
* high enough to keep threads busy, but low enough to avoid |
1693 |
* overhead and contention across threads. |
1694 |
* |
1695 |
* @return the number of steals |
1696 |
*/ |
1697 |
public long getStealCount() { |
1698 |
return stealCount; |
1699 |
} |
1700 |
|
1701 |
/** |
1702 |
* Returns an estimate of the total number of tasks currently held |
1703 |
* in queues by worker threads (but not including tasks submitted |
1704 |
* to the pool that have not begun executing). This value is only |
1705 |
* an approximation, obtained by iterating across all threads in |
1706 |
* the pool. This method may be useful for tuning task |
1707 |
* granularities. |
1708 |
* |
1709 |
* @return the number of queued tasks |
1710 |
*/ |
1711 |
public long getQueuedTaskCount() { |
1712 |
long count = 0; |
1713 |
ForkJoinWorkerThread[] ws = workers; |
1714 |
int nws = ws.length; |
1715 |
for (int i = 0; i < nws; ++i) { |
1716 |
ForkJoinWorkerThread w = ws[i]; |
1717 |
if (w != null) |
1718 |
count += w.getQueueSize(); |
1719 |
} |
1720 |
return count; |
1721 |
} |
1722 |
|
1723 |
/** |
1724 |
* Returns an estimate of the number of tasks submitted to this |
1725 |
* pool that have not yet begun executing. This method takes time |
1726 |
* proportional to the number of submissions. |
1727 |
* |
1728 |
* @return the number of queued submissions |
1729 |
*/ |
1730 |
public int getQueuedSubmissionCount() { |
1731 |
return submissionQueue.size(); |
1732 |
} |
1733 |
|
1734 |
/** |
1735 |
* Returns {@code true} if there are any tasks submitted to this |
1736 |
* pool that have not yet begun executing. |
1737 |
* |
1738 |
* @return {@code true} if there are any queued submissions |
1739 |
*/ |
1740 |
public boolean hasQueuedSubmissions() { |
1741 |
return !submissionQueue.isEmpty(); |
1742 |
} |
1743 |
|
1744 |
/** |
1745 |
* Removes and returns the next unexecuted submission if one is |
1746 |
* available. This method may be useful in extensions to this |
1747 |
* class that re-assign work in systems with multiple pools. |
1748 |
* |
1749 |
* @return the next submission, or {@code null} if none |
1750 |
*/ |
1751 |
protected ForkJoinTask<?> pollSubmission() { |
1752 |
return submissionQueue.poll(); |
1753 |
} |
1754 |
|
1755 |
/** |
1756 |
* Removes all available unexecuted submitted and forked tasks |
1757 |
* from scheduling queues and adds them to the given collection, |
1758 |
* without altering their execution status. These may include |
1759 |
* artificially generated or wrapped tasks. This method is |
1760 |
* designed to be invoked only when the pool is known to be |
1761 |
* quiescent. Invocations at other times may not remove all |
1762 |
* tasks. A failure encountered while attempting to add elements |
1763 |
* to collection {@code c} may result in elements being in |
1764 |
* neither, either or both collections when the associated |
1765 |
* exception is thrown. The behavior of this operation is |
1766 |
* undefined if the specified collection is modified while the |
1767 |
* operation is in progress. |
1768 |
* |
1769 |
* @param c the collection to transfer elements into |
1770 |
* @return the number of elements transferred |
1771 |
*/ |
1772 |
protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) { |
1773 |
int n = submissionQueue.drainTo(c); |
1774 |
ForkJoinWorkerThread[] ws = workers; |
1775 |
int nws = ws.length; |
1776 |
for (int i = 0; i < nws; ++i) { |
1777 |
ForkJoinWorkerThread w = ws[i]; |
1778 |
if (w != null) |
1779 |
n += w.drainTasksTo(c); |
1780 |
} |
1781 |
return n; |
1782 |
} |
1783 |
|
1784 |
/** |
1785 |
* Returns a string identifying this pool, as well as its state, |
1786 |
* including indications of run state, parallelism level, and |
1787 |
* worker and task counts. |
1788 |
* |
1789 |
* @return a string identifying this pool, as well as its state |
1790 |
*/ |
1791 |
public String toString() { |
1792 |
long st = getStealCount(); |
1793 |
long qt = getQueuedTaskCount(); |
1794 |
long qs = getQueuedSubmissionCount(); |
1795 |
int wc = workerCounts; |
1796 |
int tc = wc >>> TOTAL_COUNT_SHIFT; |
1797 |
int rc = wc & RUNNING_COUNT_MASK; |
1798 |
int pc = parallelism; |
1799 |
int rs = runState; |
1800 |
int ac = rs & ACTIVE_COUNT_MASK; |
1801 |
return super.toString() + |
1802 |
"[" + runLevelToString(rs) + |
1803 |
", parallelism = " + pc + |
1804 |
", size = " + tc + |
1805 |
", active = " + ac + |
1806 |
", running = " + rc + |
1807 |
", steals = " + st + |
1808 |
", tasks = " + qt + |
1809 |
", submissions = " + qs + |
1810 |
"]"; |
1811 |
} |
1812 |
|
1813 |
private static String runLevelToString(int s) { |
1814 |
return ((s & TERMINATED) != 0 ? "Terminated" : |
1815 |
((s & TERMINATING) != 0 ? "Terminating" : |
1816 |
((s & SHUTDOWN) != 0 ? "Shutting down" : |
1817 |
"Running"))); |
1818 |
} |
1819 |
|
1820 |
/** |
1821 |
* Initiates an orderly shutdown in which previously submitted |
1822 |
* tasks are executed, but no new tasks will be accepted. |
1823 |
* Invocation has no additional effect if already shut down. |
1824 |
* Tasks that are in the process of being submitted concurrently |
1825 |
* during the course of this method may or may not be rejected. |
1826 |
* |
1827 |
* @throws SecurityException if a security manager exists and |
1828 |
* the caller is not permitted to modify threads |
1829 |
* because it does not hold {@link |
1830 |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
1831 |
*/ |
1832 |
public void shutdown() { |
1833 |
checkPermission(); |
1834 |
advanceRunLevel(SHUTDOWN); |
1835 |
tryTerminate(false); |
1836 |
} |
1837 |
|
1838 |
/** |
1839 |
* Attempts to cancel and/or stop all tasks, and reject all |
1840 |
* subsequently submitted tasks. Tasks that are in the process of |
1841 |
* being submitted or executed concurrently during the course of |
1842 |
* this method may or may not be rejected. This method cancels |
1843 |
* both existing and unexecuted tasks, in order to permit |
1844 |
* termination in the presence of task dependencies. So the method |
1845 |
* always returns an empty list (unlike the case for some other |
1846 |
* Executors). |
1847 |
* |
1848 |
* @return an empty list |
1849 |
* @throws SecurityException if a security manager exists and |
1850 |
* the caller is not permitted to modify threads |
1851 |
* because it does not hold {@link |
1852 |
* java.lang.RuntimePermission}{@code ("modifyThread")} |
1853 |
*/ |
1854 |
public List<Runnable> shutdownNow() { |
1855 |
checkPermission(); |
1856 |
tryTerminate(true); |
1857 |
return Collections.emptyList(); |
1858 |
} |
1859 |
|
1860 |
/** |
1861 |
* Returns {@code true} if all tasks have completed following shut down. |
1862 |
* |
1863 |
* @return {@code true} if all tasks have completed following shut down |
1864 |
*/ |
1865 |
public boolean isTerminated() { |
1866 |
return runState >= TERMINATED; |
1867 |
} |
1868 |
|
1869 |
/** |
1870 |
* Returns {@code true} if the process of termination has |
1871 |
* commenced but not yet completed. This method may be useful for |
1872 |
* debugging. A return of {@code true} reported a sufficient |
1873 |
* period after shutdown may indicate that submitted tasks have |
1874 |
* ignored or suppressed interruption, causing this executor not |
1875 |
* to properly terminate. |
1876 |
* |
1877 |
* @return {@code true} if terminating but not yet terminated |
1878 |
*/ |
1879 |
public boolean isTerminating() { |
1880 |
return (runState & (TERMINATING|TERMINATED)) == TERMINATING; |
1881 |
} |
1882 |
|
1883 |
/** |
1884 |
* Returns {@code true} if this pool has been shut down. |
1885 |
* |
1886 |
* @return {@code true} if this pool has been shut down |
1887 |
*/ |
1888 |
public boolean isShutdown() { |
1889 |
return runState >= SHUTDOWN; |
1890 |
} |
1891 |
|
1892 |
/** |
1893 |
* Blocks until all tasks have completed execution after a shutdown |
1894 |
* request, or the timeout occurs, or the current thread is |
1895 |
* interrupted, whichever happens first. |
1896 |
* |
1897 |
* @param timeout the maximum time to wait |
1898 |
* @param unit the time unit of the timeout argument |
1899 |
* @return {@code true} if this executor terminated and |
1900 |
* {@code false} if the timeout elapsed before termination |
1901 |
* @throws InterruptedException if interrupted while waiting |
1902 |
*/ |
1903 |
public boolean awaitTermination(long timeout, TimeUnit unit) |
1904 |
throws InterruptedException { |
1905 |
return terminationLatch.await(timeout, unit); |
1906 |
} |
1907 |
|
1908 |
/** |
1909 |
* Interface for extending managed parallelism for tasks running |
1910 |
* in {@link ForkJoinPool}s. |
1911 |
* |
1912 |
* <p>A {@code ManagedBlocker} provides two methods. |
1913 |
* Method {@code isReleasable} must return {@code true} if |
1914 |
* blocking is not necessary. Method {@code block} blocks the |
1915 |
* current thread if necessary (perhaps internally invoking |
1916 |
* {@code isReleasable} before actually blocking). |
1917 |
* |
1918 |
* <p>For example, here is a ManagedBlocker based on a |
1919 |
* ReentrantLock: |
1920 |
* <pre> {@code |
1921 |
* class ManagedLocker implements ManagedBlocker { |
1922 |
* final ReentrantLock lock; |
1923 |
* boolean hasLock = false; |
1924 |
* ManagedLocker(ReentrantLock lock) { this.lock = lock; } |
1925 |
* public boolean block() { |
1926 |
* if (!hasLock) |
1927 |
* lock.lock(); |
1928 |
* return true; |
1929 |
* } |
1930 |
* public boolean isReleasable() { |
1931 |
* return hasLock || (hasLock = lock.tryLock()); |
1932 |
* } |
1933 |
* }}</pre> |
1934 |
*/ |
1935 |
public static interface ManagedBlocker { |
1936 |
/** |
1937 |
* Possibly blocks the current thread, for example waiting for |
1938 |
* a lock or condition. |
1939 |
* |
1940 |
* @return {@code true} if no additional blocking is necessary |
1941 |
* (i.e., if isReleasable would return true) |
1942 |
* @throws InterruptedException if interrupted while waiting |
1943 |
* (the method is not required to do so, but is allowed to) |
1944 |
*/ |
1945 |
boolean block() throws InterruptedException; |
1946 |
|
1947 |
/** |
1948 |
* Returns {@code true} if blocking is unnecessary. |
1949 |
*/ |
1950 |
boolean isReleasable(); |
1951 |
} |
1952 |
|
1953 |
/** |
1954 |
* Blocks in accord with the given blocker. If the current thread |
1955 |
* is a {@link ForkJoinWorkerThread}, this method possibly |
1956 |
* arranges for a spare thread to be activated if necessary to |
1957 |
* ensure parallelism while the current thread is blocked. |
1958 |
* |
1959 |
* <p>If {@code maintainParallelism} is {@code true} and the pool |
1960 |
* supports it ({@link #getMaintainsParallelism}), this method |
1961 |
* attempts to maintain the pool's nominal parallelism. Otherwise |
1962 |
* it activates a thread only if necessary to avoid complete |
1963 |
* starvation. This option may be preferable when blockages use |
1964 |
* timeouts, or are almost always brief. |
1965 |
* |
1966 |
* <p>If the caller is not a {@link ForkJoinTask}, this method is |
1967 |
* behaviorally equivalent to |
1968 |
* <pre> {@code |
1969 |
* while (!blocker.isReleasable()) |
1970 |
* if (blocker.block()) |
1971 |
* return; |
1972 |
* }</pre> |
1973 |
* |
1974 |
* If the caller is a {@code ForkJoinTask}, then the pool may |
1975 |
* first be expanded to ensure parallelism, and later adjusted. |
1976 |
* |
1977 |
* @param blocker the blocker |
1978 |
* @param maintainParallelism if {@code true} and supported by |
1979 |
* this pool, attempt to maintain the pool's nominal parallelism; |
1980 |
* otherwise activate a thread only if necessary to avoid |
1981 |
* complete starvation. |
1982 |
* @throws InterruptedException if blocker.block did so |
1983 |
*/ |
1984 |
public static void managedBlock(ManagedBlocker blocker, |
1985 |
boolean maintainParallelism) |
1986 |
throws InterruptedException { |
1987 |
Thread t = Thread.currentThread(); |
1988 |
if (t instanceof ForkJoinWorkerThread) |
1989 |
((ForkJoinWorkerThread) t).pool. |
1990 |
awaitBlocker(blocker, maintainParallelism); |
1991 |
else |
1992 |
awaitBlocker(blocker); |
1993 |
} |
1994 |
|
1995 |
/** |
1996 |
* Performs Non-FJ blocking |
1997 |
*/ |
1998 |
private static void awaitBlocker(ManagedBlocker blocker) |
1999 |
throws InterruptedException { |
2000 |
do {} while (!blocker.isReleasable() && !blocker.block()); |
2001 |
} |
2002 |
|
2003 |
// AbstractExecutorService overrides. These rely on undocumented |
2004 |
// fact that ForkJoinTask.adapt returns ForkJoinTasks that also |
2005 |
// implement RunnableFuture. |
2006 |
|
2007 |
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) { |
2008 |
return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value); |
2009 |
} |
2010 |
|
2011 |
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) { |
2012 |
return (RunnableFuture<T>) ForkJoinTask.adapt(callable); |
2013 |
} |
2014 |
|
2015 |
// Unsafe mechanics |
2016 |
|
2017 |
private static final sun.misc.Unsafe UNSAFE = getUnsafe(); |
2018 |
private static final long workerCountsOffset = |
2019 |
objectFieldOffset("workerCounts", ForkJoinPool.class); |
2020 |
private static final long runStateOffset = |
2021 |
objectFieldOffset("runState", ForkJoinPool.class); |
2022 |
private static final long eventCountOffset = |
2023 |
objectFieldOffset("eventCount", ForkJoinPool.class); |
2024 |
private static final long eventWaitersOffset = |
2025 |
objectFieldOffset("eventWaiters",ForkJoinPool.class); |
2026 |
private static final long stealCountOffset = |
2027 |
objectFieldOffset("stealCount",ForkJoinPool.class); |
2028 |
|
2029 |
|
2030 |
private static long objectFieldOffset(String field, Class<?> klazz) { |
2031 |
try { |
2032 |
return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field)); |
2033 |
} catch (NoSuchFieldException e) { |
2034 |
// Convert Exception to corresponding Error |
2035 |
NoSuchFieldError error = new NoSuchFieldError(field); |
2036 |
error.initCause(e); |
2037 |
throw error; |
2038 |
} |
2039 |
} |
2040 |
|
2041 |
/** |
2042 |
* Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. |
2043 |
* Replace with a simple call to Unsafe.getUnsafe when integrating |
2044 |
* into a jdk. |
2045 |
* |
2046 |
* @return a sun.misc.Unsafe |
2047 |
*/ |
2048 |
private static sun.misc.Unsafe getUnsafe() { |
2049 |
try { |
2050 |
return sun.misc.Unsafe.getUnsafe(); |
2051 |
} catch (SecurityException se) { |
2052 |
try { |
2053 |
return java.security.AccessController.doPrivileged |
2054 |
(new java.security |
2055 |
.PrivilegedExceptionAction<sun.misc.Unsafe>() { |
2056 |
public sun.misc.Unsafe run() throws Exception { |
2057 |
java.lang.reflect.Field f = sun.misc |
2058 |
.Unsafe.class.getDeclaredField("theUnsafe"); |
2059 |
f.setAccessible(true); |
2060 |
return (sun.misc.Unsafe) f.get(null); |
2061 |
}}); |
2062 |
} catch (java.security.PrivilegedActionException e) { |
2063 |
throw new RuntimeException("Could not initialize intrinsics", |
2064 |
e.getCause()); |
2065 |
} |
2066 |
} |
2067 |
} |
2068 |
} |