ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.23
Committed: Wed Aug 18 14:05:51 2010 UTC (13 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.22: +2 -2 lines
Log Message:
Fix typos in example

File Contents

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