ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinWorkerThread.java
Revision: 1.40
Committed: Sun Nov 21 08:50:12 2010 UTC (13 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.39: +10 -9 lines
Log Message:
add @links to ForkJoinTask

File Contents

# User Rev Content
1 jsr166 1.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 dl 1.14 import java.util.Random;
10 jsr166 1.1 import java.util.Collection;
11 dl 1.14 import java.util.concurrent.locks.LockSupport;
12 dl 1.34 import java.util.concurrent.RejectedExecutionException;
13 jsr166 1.1
14     /**
15 jsr166 1.40 * A thread managed by a {@link ForkJoinPool}, which executes
16     * {@link ForkJoinTask}s.
17     * This class is subclassable solely for the sake of adding
18     * functionality -- there are no overridable methods dealing with
19     * scheduling or execution. However, you can override initialization
20     * and termination methods surrounding the main task processing loop.
21     * If you do create such a subclass, you will also need to supply a
22     * custom {@link ForkJoinPool.ForkJoinWorkerThreadFactory} to use it
23     * in a {@code ForkJoinPool}.
24 jsr166 1.1 *
25     * @since 1.7
26     * @author Doug Lea
27     */
28     public class ForkJoinWorkerThread extends Thread {
29     /*
30 dl 1.14 * Overview:
31 jsr166 1.1 *
32 dl 1.14 * ForkJoinWorkerThreads are managed by ForkJoinPools and perform
33     * ForkJoinTasks. This class includes bookkeeping in support of
34     * worker activation, suspension, and lifecycle control described
35     * in more detail in the internal documentation of class
36     * ForkJoinPool. And as described further below, this class also
37     * includes special-cased support for some ForkJoinTask
38     * methods. But the main mechanics involve work-stealing:
39     *
40     * Work-stealing queues are special forms of Deques that support
41     * only three of the four possible end-operations -- push, pop,
42     * and deq (aka steal), under the further constraints that push
43     * and pop are called only from the owning thread, while deq may
44     * be called from other threads. (If you are unfamiliar with
45     * them, you probably want to read Herlihy and Shavit's book "The
46     * Art of Multiprocessor programming", chapter 16 describing these
47     * in more detail before proceeding.) The main work-stealing
48     * queue design is roughly similar to those in the papers "Dynamic
49     * Circular Work-Stealing Deque" by Chase and Lev, SPAA 2005
50     * (http://research.sun.com/scalable/pubs/index.html) and
51     * "Idempotent work stealing" by Michael, Saraswat, and Vechev,
52     * PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186).
53     * The main differences ultimately stem from gc requirements that
54     * we null out taken slots as soon as we can, to maintain as small
55     * a footprint as possible even in programs generating huge
56     * numbers of tasks. To accomplish this, we shift the CAS
57     * arbitrating pop vs deq (steal) from being on the indices
58     * ("base" and "sp") to the slots themselves (mainly via method
59     * "casSlotNull()"). So, both a successful pop and deq mainly
60     * entail a CAS of a slot from non-null to null. Because we rely
61     * on CASes of references, we do not need tag bits on base or sp.
62     * They are simple ints as used in any circular array-based queue
63     * (see for example ArrayDeque). Updates to the indices must
64     * still be ordered in a way that guarantees that sp == base means
65     * the queue is empty, but otherwise may err on the side of
66     * possibly making the queue appear nonempty when a push, pop, or
67     * deq have not fully committed. Note that this means that the deq
68     * operation, considered individually, is not wait-free. One thief
69     * cannot successfully continue until another in-progress one (or,
70     * if previously empty, a push) completes. However, in the
71     * aggregate, we ensure at least probabilistic non-blockingness.
72     * If an attempted steal fails, a thief always chooses a different
73     * random victim target to try next. So, in order for one thief to
74     * progress, it suffices for any in-progress deq or new push on
75     * any empty queue to complete. One reason this works well here is
76     * that apparently-nonempty often means soon-to-be-stealable,
77     * which gives threads a chance to set activation status if
78     * necessary before stealing.
79 jsr166 1.1 *
80 jsr166 1.6 * This approach also enables support for "async mode" where local
81     * task processing is in FIFO, not LIFO order; simply by using a
82     * version of deq rather than pop when locallyFifo is true (as set
83     * by the ForkJoinPool). This allows use in message-passing
84     * frameworks in which tasks are never joined.
85     *
86 dl 1.17 * When a worker would otherwise be blocked waiting to join a
87     * task, it first tries a form of linear helping: Each worker
88 dl 1.18 * records (in field currentSteal) the most recent task it stole
89     * from some other worker. Plus, it records (in field currentJoin)
90     * the task it is currently actively joining. Method joinTask uses
91 dl 1.17 * these markers to try to find a worker to help (i.e., steal back
92     * a task from and execute it) that could hasten completion of the
93     * actively joined task. In essence, the joiner executes a task
94     * that would be on its own local deque had the to-be-joined task
95     * not been stolen. This may be seen as a conservative variant of
96     * the approach in Wagner & Calder "Leapfrogging: a portable
97     * technique for implementing efficient futures" SIGPLAN Notices,
98     * 1993 (http://portal.acm.org/citation.cfm?id=155354). It differs
99     * in that: (1) We only maintain dependency links across workers
100 dl 1.18 * upon steals, rather than use per-task bookkeeping. This may
101     * require a linear scan of workers array to locate stealers, but
102     * usually doesn't because stealers leave hints (that may become
103     * stale/wrong) of where to locate them. This isolates cost to
104     * when it is needed, rather than adding to per-task overhead.
105     * (2) It is "shallow", ignoring nesting and potentially cyclic
106     * mutual steals. (3) It is intentionally racy: field currentJoin
107     * is updated only while actively joining, which means that we
108     * miss links in the chain during long-lived tasks, GC stalls etc
109     * (which is OK since blocking in such cases is usually a good
110     * idea). (4) We bound the number of attempts to find work (see
111     * MAX_HELP_DEPTH) and fall back to suspending the worker and if
112     * necessary replacing it with a spare (see
113 dl 1.20 * ForkJoinPool.awaitJoin).
114 dl 1.17 *
115 dl 1.18 * Efficient implementation of these algorithms currently relies
116     * on an uncomfortable amount of "Unsafe" mechanics. To maintain
117 jsr166 1.1 * correct orderings, reads and writes of variable base require
118 dl 1.14 * volatile ordering. Variable sp does not require volatile
119     * writes but still needs store-ordering, which we accomplish by
120     * pre-incrementing sp before filling the slot with an ordered
121     * store. (Pre-incrementing also enables backouts used in
122 dl 1.18 * joinTask.) Because they are protected by volatile base reads,
123     * reads of the queue array and its slots by other threads do not
124     * need volatile load semantics, but writes (in push) require
125     * store order and CASes (in pop and deq) require (volatile) CAS
126     * semantics. (Michael, Saraswat, and Vechev's algorithm has
127     * similar properties, but without support for nulling slots.)
128     * Since these combinations aren't supported using ordinary
129     * volatiles, the only way to accomplish these efficiently is to
130     * use direct Unsafe calls. (Using external AtomicIntegers and
131     * AtomicReferenceArrays for the indices and array is
132     * significantly slower because of memory locality and indirection
133     * effects.)
134 jsr166 1.9 *
135 jsr166 1.8 * Further, performance on most platforms is very sensitive to
136     * placement and sizing of the (resizable) queue array. Even
137     * though these queues don't usually become all that big, the
138     * initial size must be large enough to counteract cache
139 jsr166 1.1 * contention effects across multiple queues (especially in the
140     * presence of GC cardmarking). Also, to improve thread-locality,
141 dl 1.14 * queues are initialized after starting. All together, these
142     * low-level implementation choices produce as much as a factor of
143     * 4 performance improvement compared to naive implementations,
144     * and enable the processing of billions of tasks per second,
145     * sometimes at the expense of ugliness.
146 jsr166 1.1 */
147    
148     /**
149 dl 1.14 * Generator for initial random seeds for random victim
150     * selection. This is used only to create initial seeds. Random
151     * steals use a cheaper xorshift generator per steal attempt. We
152     * expect only rare contention on seedGenerator, so just use a
153     * plain Random.
154     */
155     private static final Random seedGenerator = new Random();
156    
157     /**
158 dl 1.18 * The maximum stolen->joining link depth allowed in helpJoinTask.
159     * Depths for legitimate chains are unbounded, but we use a fixed
160     * constant to avoid (otherwise unchecked) cycles and bound
161     * staleness of traversal parameters at the expense of sometimes
162     * blocking when we could be helping.
163 dl 1.14 */
164 dl 1.18 private static final int MAX_HELP_DEPTH = 8;
165    
166     /**
167 jsr166 1.1 * Capacity of work-stealing queue array upon initialization.
168 dl 1.17 * Must be a power of two. Initial size must be at least 4, but is
169 jsr166 1.1 * padded to minimize cache effects.
170     */
171     private static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
172    
173     /**
174     * Maximum work-stealing queue array size. Must be less than or
175 dl 1.24 * equal to 1 << (31 - width of array entry) to ensure lack of
176     * index wraparound. The value is set in the static block
177     * at the end of this file after obtaining width.
178 jsr166 1.1 */
179 dl 1.24 private static final int MAXIMUM_QUEUE_CAPACITY;
180 jsr166 1.1
181     /**
182     * The pool this thread works in. Accessed directly by ForkJoinTask.
183     */
184     final ForkJoinPool pool;
185    
186     /**
187     * The work-stealing queue array. Size must be a power of two.
188 dl 1.14 * Initialized in onStart, to improve memory locality.
189 jsr166 1.1 */
190     private ForkJoinTask<?>[] queue;
191    
192     /**
193 dl 1.14 * Index (mod queue.length) of least valid queue slot, which is
194     * always the next position to steal from if nonempty.
195     */
196     private volatile int base;
197    
198     /**
199 jsr166 1.1 * Index (mod queue.length) of next queue slot to push to or pop
200 dl 1.14 * from. It is written only by owner thread, and accessed by other
201     * threads only after reading (volatile) base. Both sp and base
202     * are allowed to wrap around on overflow, but (sp - base) still
203     * estimates size.
204     */
205     private int sp;
206 jsr166 1.1
207     /**
208 dl 1.18 * The index of most recent stealer, used as a hint to avoid
209     * traversal in method helpJoinTask. This is only a hint because a
210     * worker might have had multiple steals and this only holds one
211     * of them (usually the most current). Declared non-volatile,
212     * relying on other prevailing sync to keep reasonably current.
213     */
214     private int stealHint;
215    
216     /**
217 dl 1.14 * Run state of this worker. In addition to the usual run levels,
218     * tracks if this worker is suspended as a spare, and if it was
219     * killed (trimmed) while suspended. However, "active" status is
220 dl 1.19 * maintained separately and modified only in conjunction with
221 dl 1.20 * CASes of the pool's runState (which are currently sadly
222     * manually inlined for performance.) Accessed directly by pool
223     * to simplify checks for normal (zero) status.
224 jsr166 1.1 */
225 dl 1.20 volatile int runState;
226 dl 1.14
227     private static final int TERMINATING = 0x01;
228     private static final int TERMINATED = 0x02;
229     private static final int SUSPENDED = 0x04; // inactive spare
230     private static final int TRIMMED = 0x08; // killed while suspended
231 jsr166 1.1
232     /**
233 dl 1.21 * Number of steals. Directly accessed (and reset) by
234     * pool.tryAccumulateStealCount when idle.
235 jsr166 1.1 */
236 dl 1.14 int stealCount;
237 jsr166 1.1
238     /**
239     * Seed for random number generator for choosing steal victims.
240 dl 1.14 * Uses Marsaglia xorshift. Must be initialized as nonzero.
241 jsr166 1.1 */
242     private int seed;
243    
244     /**
245 dl 1.14 * Activity status. When true, this worker is considered active.
246     * Accessed directly by pool. Must be false upon construction.
247     */
248     boolean active;
249    
250     /**
251     * True if use local fifo, not default lifo, for local polling.
252 dl 1.18 * Shadows value from ForkJoinPool.
253 jsr166 1.1 */
254 dl 1.17 private final boolean locallyFifo;
255 dl 1.18
256 jsr166 1.1 /**
257     * Index of this worker in pool array. Set once by pool before
258 dl 1.14 * running, and accessed directly by pool to locate this worker in
259     * its workers array.
260 jsr166 1.1 */
261     int poolIndex;
262    
263     /**
264 dl 1.14 * The last pool event waited for. Accessed only by pool in
265     * callback methods invoked within this thread.
266 jsr166 1.1 */
267 dl 1.14 int lastEventCount;
268 jsr166 1.1
269     /**
270 dl 1.20 * Encoded index and event count of next event waiter. Accessed
271     * only by ForkJoinPool for managing event waiters.
272 jsr166 1.1 */
273 dl 1.14 volatile long nextWaiter;
274 jsr166 1.1
275     /**
276 dl 1.20 * Number of times this thread suspended as spare. Accessed only
277     * by pool.
278 dl 1.18 */
279     int spareCount;
280    
281     /**
282 dl 1.20 * Encoded index and count of next spare waiter. Accessed only
283 dl 1.18 * by ForkJoinPool for managing spares.
284     */
285     volatile int nextSpare;
286    
287     /**
288     * The task currently being joined, set only when actively trying
289 dl 1.26 * to help other stealers in helpJoinTask. Written only by this
290 dl 1.21 * thread, but read by others.
291 dl 1.18 */
292     private volatile ForkJoinTask<?> currentJoin;
293    
294     /**
295     * The task most recently stolen from another worker (or
296 dl 1.26 * submission queue). Written only by this thread, but read by
297 dl 1.20 * others.
298 dl 1.18 */
299 dl 1.20 private volatile ForkJoinTask<?> currentSteal;
300 dl 1.18
301     /**
302 jsr166 1.1 * Creates a ForkJoinWorkerThread operating in the given pool.
303     *
304     * @param pool the pool this thread works in
305     * @throws NullPointerException if pool is null
306     */
307     protected ForkJoinWorkerThread(ForkJoinPool pool) {
308     this.pool = pool;
309 dl 1.17 this.locallyFifo = pool.locallyFifo;
310 dl 1.18 setDaemon(true);
311 dl 1.14 // To avoid exposing construction details to subclasses,
312     // remaining initialization is in start() and onStart()
313 jsr166 1.1 }
314    
315 dl 1.14 /**
316 jsr166 1.25 * Performs additional initialization and starts this thread.
317 dl 1.14 */
318 dl 1.17 final void start(int poolIndex, UncaughtExceptionHandler ueh) {
319 dl 1.14 this.poolIndex = poolIndex;
320     if (ueh != null)
321     setUncaughtExceptionHandler(ueh);
322     start();
323     }
324    
325     // Public/protected methods
326 jsr166 1.1
327     /**
328     * Returns the pool hosting this thread.
329     *
330     * @return the pool
331     */
332     public ForkJoinPool getPool() {
333     return pool;
334     }
335    
336     /**
337     * Returns the index number of this thread in its pool. The
338     * returned value ranges from zero to the maximum number of
339     * threads (minus one) that have ever been created in the pool.
340     * This method may be useful for applications that track status or
341     * collect results per-worker rather than per-task.
342     *
343     * @return the index number
344     */
345     public int getPoolIndex() {
346     return poolIndex;
347     }
348    
349     /**
350 dl 1.14 * Initializes internal state after construction but before
351     * processing any tasks. If you override this method, you must
352 jsr166 1.39 * invoke {@code super.onStart()} at the beginning of the method.
353 dl 1.14 * Initialization requires care: Most fields must have legal
354     * default values, to ensure that attempted accesses from other
355     * threads work correctly even before this thread starts
356     * processing tasks.
357 jsr166 1.1 */
358 dl 1.14 protected void onStart() {
359     int rs = seedGenerator.nextInt();
360     seed = rs == 0? 1 : rs; // seed must be nonzero
361 jsr166 1.1
362 dl 1.17 // Allocate name string and arrays in this thread
363 dl 1.14 String pid = Integer.toString(pool.getPoolNumber());
364     String wid = Integer.toString(poolIndex);
365     setName("ForkJoinPool-" + pid + "-worker-" + wid);
366 jsr166 1.1
367 dl 1.14 queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
368     }
369 jsr166 1.1
370     /**
371 dl 1.14 * Performs cleanup associated with termination of this worker
372     * thread. If you override this method, you must invoke
373     * {@code super.onTermination} at the end of the overridden method.
374 jsr166 1.4 *
375 dl 1.14 * @param exception the exception causing this thread to abort due
376     * to an unrecoverable error, or {@code null} if completed normally
377 jsr166 1.1 */
378 dl 1.14 protected void onTermination(Throwable exception) {
379     try {
380 dl 1.19 ForkJoinPool p = pool;
381     if (active) {
382     int a; // inline p.tryDecrementActiveCount
383     active = false;
384 jsr166 1.22 do {} while (!UNSAFE.compareAndSwapInt
385     (p, poolRunStateOffset, a = p.runState, a - 1));
386 dl 1.19 }
387 dl 1.14 cancelTasks();
388     setTerminated();
389 dl 1.19 p.workerTerminated(this);
390 dl 1.14 } catch (Throwable ex) { // Shouldn't ever happen
391     if (exception == null) // but if so, at least rethrown
392     exception = ex;
393     } finally {
394     if (exception != null)
395     UNSAFE.throwException(exception);
396 jsr166 1.1 }
397     }
398    
399     /**
400     * This method is required to be public, but should never be
401     * called explicitly. It performs the main run loop to execute
402 jsr166 1.40 * {@link ForkJoinTask}s.
403 jsr166 1.1 */
404     public void run() {
405     Throwable exception = null;
406     try {
407     onStart();
408     mainLoop();
409     } catch (Throwable ex) {
410     exception = ex;
411     } finally {
412     onTermination(exception);
413     }
414     }
415    
416 dl 1.14 // helpers for run()
417    
418 jsr166 1.1 /**
419 jsr166 1.25 * Finds and executes tasks, and checks status while running.
420 jsr166 1.1 */
421     private void mainLoop() {
422 dl 1.20 boolean ran = false; // true if ran a task on last step
423 dl 1.14 ForkJoinPool p = pool;
424     for (;;) {
425 dl 1.20 p.preStep(this, ran);
426 dl 1.14 if (runState != 0)
427 dl 1.18 break;
428 dl 1.20 ran = tryExecSteal() || tryExecSubmission();
429 jsr166 1.1 }
430     }
431    
432     /**
433 jsr166 1.25 * Tries to steal a task and execute it.
434 dl 1.18 *
435     * @return true if ran a task
436 jsr166 1.1 */
437 dl 1.18 private boolean tryExecSteal() {
438     ForkJoinTask<?> t;
439 dl 1.20 if ((t = scan()) != null) {
440 dl 1.18 t.quietlyExec();
441 dl 1.20 UNSAFE.putOrderedObject(this, currentStealOffset, null);
442 dl 1.18 if (sp != base)
443     execLocalTasks();
444     return true;
445 dl 1.14 }
446 dl 1.18 return false;
447 jsr166 1.1 }
448    
449     /**
450 dl 1.21 * If a submission exists, try to activate and run it.
451 jsr166 1.1 *
452 dl 1.18 * @return true if ran a task
453 jsr166 1.1 */
454 dl 1.18 private boolean tryExecSubmission() {
455 dl 1.14 ForkJoinPool p = pool;
456 dl 1.21 // This loop is needed in case attempt to activate fails, in
457     // which case we only retry if there still appears to be a
458     // submission.
459 dl 1.14 while (p.hasQueuedSubmissions()) {
460 dl 1.19 ForkJoinTask<?> t; int a;
461 dl 1.20 if (active || // inline p.tryIncrementActiveCount
462 dl 1.19 (active = UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
463     a = p.runState, a + 1))) {
464 dl 1.18 if ((t = p.pollSubmission()) != null) {
465 dl 1.20 UNSAFE.putOrderedObject(this, currentStealOffset, t);
466 dl 1.18 t.quietlyExec();
467 dl 1.20 UNSAFE.putOrderedObject(this, currentStealOffset, null);
468 dl 1.18 if (sp != base)
469     execLocalTasks();
470     return true;
471     }
472 jsr166 1.1 }
473     }
474 dl 1.18 return false;
475     }
476    
477     /**
478     * Runs local tasks until queue is empty or shut down. Call only
479     * while active.
480     */
481     private void execLocalTasks() {
482     while (runState == 0) {
483 jsr166 1.23 ForkJoinTask<?> t = locallyFifo ? locallyDeqTask() : popTask();
484 dl 1.18 if (t != null)
485     t.quietlyExec();
486     else if (sp == base)
487     break;
488     }
489 jsr166 1.1 }
490    
491 dl 1.14 /*
492     * Intrinsics-based atomic writes for queue slots. These are
493 jsr166 1.28 * basically the same as methods in AtomicReferenceArray, but
494 dl 1.14 * specialized for (1) ForkJoinTask elements (2) requirement that
495     * nullness and bounds checks have already been performed by
496     * callers and (3) effective offsets are known not to overflow
497     * from int to long (because of MAXIMUM_QUEUE_CAPACITY). We don't
498     * need corresponding version for reads: plain array reads are OK
499 jsr166 1.27 * because they are protected by other volatile reads and are
500 dl 1.14 * confirmed by CASes.
501     *
502     * Most uses don't actually call these methods, but instead contain
503     * inlined forms that enable more predictable optimization. We
504     * don't define the version of write used in pushTask at all, but
505     * instead inline there a store-fenced array slot write.
506 jsr166 1.1 */
507    
508     /**
509 dl 1.14 * CASes slot i of array q from t to null. Caller must ensure q is
510     * non-null and index is in range.
511 jsr166 1.1 */
512 dl 1.14 private static final boolean casSlotNull(ForkJoinTask<?>[] q, int i,
513     ForkJoinTask<?> t) {
514     return UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null);
515 jsr166 1.1 }
516    
517     /**
518 dl 1.14 * Performs a volatile write of the given task at given slot of
519     * array q. Caller must ensure q is non-null and index is in
520     * range. This method is used only during resets and backouts.
521 jsr166 1.1 */
522 dl 1.14 private static final void writeSlot(ForkJoinTask<?>[] q, int i,
523 jsr166 1.25 ForkJoinTask<?> t) {
524 dl 1.14 UNSAFE.putObjectVolatile(q, (i << qShift) + qBase, t);
525 jsr166 1.1 }
526    
527 dl 1.14 // queue methods
528 jsr166 1.1
529     /**
530 dl 1.14 * Pushes a task. Call only from this thread.
531 jsr166 1.1 *
532     * @param t the task. Caller must ensure non-null.
533     */
534     final void pushTask(ForkJoinTask<?> t) {
535     ForkJoinTask<?>[] q = queue;
536 dl 1.14 int mask = q.length - 1; // implicit assert q != null
537 dl 1.17 int s = sp++; // ok to increment sp before slot write
538     UNSAFE.putOrderedObject(q, ((s & mask) << qShift) + qBase, t);
539     if ((s -= base) == 0)
540     pool.signalWork(); // was empty
541     else if (s == mask)
542     growQueue(); // is full
543 jsr166 1.1 }
544    
545     /**
546     * Tries to take a task from the base of the queue, failing if
547 dl 1.14 * empty or contended. Note: Specializations of this code appear
548 dl 1.17 * in locallyDeqTask and elsewhere.
549 jsr166 1.1 *
550     * @return a task, or null if none or contended
551     */
552     final ForkJoinTask<?> deqTask() {
553     ForkJoinTask<?> t;
554     ForkJoinTask<?>[] q;
555 dl 1.14 int b, i;
556 dl 1.18 if (sp != (b = base) &&
557 jsr166 1.1 (q = queue) != null && // must read q after b
558 dl 1.17 (t = q[i = (q.length - 1) & b]) != null && base == b &&
559 dl 1.14 UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) {
560 jsr166 1.1 base = b + 1;
561     return t;
562     }
563     return null;
564     }
565    
566     /**
567 dl 1.14 * Tries to take a task from the base of own queue. Assumes active
568 dl 1.26 * status. Called only by this thread.
569 jsr166 1.6 *
570     * @return a task, or null if none
571     */
572     final ForkJoinTask<?> locallyDeqTask() {
573 dl 1.14 ForkJoinTask<?>[] q = queue;
574     if (q != null) {
575     ForkJoinTask<?> t;
576     int b, i;
577     while (sp != (b = base)) {
578 dl 1.17 if ((t = q[i = (q.length - 1) & b]) != null && base == b &&
579 dl 1.14 UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase,
580     t, null)) {
581 jsr166 1.6 base = b + 1;
582     return t;
583     }
584     }
585     }
586     return null;
587     }
588    
589     /**
590 dl 1.14 * Returns a popped task, or null if empty. Assumes active status.
591 dl 1.26 * Called only by this thread.
592 jsr166 1.1 */
593 dl 1.18 private ForkJoinTask<?> popTask() {
594     ForkJoinTask<?>[] q = queue;
595     if (q != null) {
596     int s;
597     while ((s = sp) != base) {
598     int i = (q.length - 1) & --s;
599     long u = (i << qShift) + qBase; // raw offset
600     ForkJoinTask<?> t = q[i];
601     if (t == null) // lost to stealer
602     break;
603     if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
604     sp = s; // putOrderedInt may encourage more timely write
605     // UNSAFE.putOrderedInt(this, spOffset, s);
606     return t;
607     }
608 jsr166 1.1 }
609     }
610     return null;
611     }
612    
613     /**
614 dl 1.16 * Specialized version of popTask to pop only if topmost element
615 dl 1.26 * is the given task. Called only by this thread while active.
616 jsr166 1.1 *
617     * @param t the task. Caller must ensure non-null.
618     */
619     final boolean unpushTask(ForkJoinTask<?> t) {
620 dl 1.14 int s;
621 dl 1.18 ForkJoinTask<?>[] q = queue;
622     if ((s = sp) != base && q != null &&
623 dl 1.16 UNSAFE.compareAndSwapObject
624     (q, (((q.length - 1) & --s) << qShift) + qBase, t, null)) {
625 dl 1.20 sp = s; // putOrderedInt may encourage more timely write
626 dl 1.18 // UNSAFE.putOrderedInt(this, spOffset, s);
627 jsr166 1.1 return true;
628     }
629     return false;
630     }
631    
632     /**
633 jsr166 1.25 * Returns next task, or null if empty or contended.
634 jsr166 1.1 */
635     final ForkJoinTask<?> peekTask() {
636     ForkJoinTask<?>[] q = queue;
637     if (q == null)
638     return null;
639     int mask = q.length - 1;
640     int i = locallyFifo ? base : (sp - 1);
641     return q[i & mask];
642     }
643    
644     /**
645     * Doubles queue array size. Transfers elements by emulating
646     * steals (deqs) from old array and placing, oldest first, into
647     * new array.
648     */
649     private void growQueue() {
650     ForkJoinTask<?>[] oldQ = queue;
651     int oldSize = oldQ.length;
652     int newSize = oldSize << 1;
653     if (newSize > MAXIMUM_QUEUE_CAPACITY)
654     throw new RejectedExecutionException("Queue capacity exceeded");
655     ForkJoinTask<?>[] newQ = queue = new ForkJoinTask<?>[newSize];
656    
657     int b = base;
658     int bf = b + oldSize;
659     int oldMask = oldSize - 1;
660     int newMask = newSize - 1;
661     do {
662     int oldIndex = b & oldMask;
663     ForkJoinTask<?> t = oldQ[oldIndex];
664     if (t != null && !casSlotNull(oldQ, oldIndex, t))
665     t = null;
666 dl 1.14 writeSlot(newQ, b & newMask, t);
667 jsr166 1.1 } while (++b != bf);
668     pool.signalWork();
669     }
670    
671     /**
672 dl 1.14 * Computes next value for random victim probe in scan(). Scans
673     * don't require a very high quality generator, but also not a
674     * crummy one. Marsaglia xor-shift is cheap and works well enough.
675 jsr166 1.25 * Note: This is manually inlined in scan().
676 dl 1.14 */
677     private static final int xorShift(int r) {
678     r ^= r << 13;
679     r ^= r >>> 17;
680     return r ^ (r << 5);
681     }
682    
683     /**
684 jsr166 1.1 * Tries to steal a task from another worker. Starts at a random
685     * index of workers array, and probes workers until finding one
686     * with non-empty queue or finding that all are empty. It
687     * randomly selects the first n probes. If these are empty, it
688 dl 1.14 * resorts to a circular sweep, which is necessary to accurately
689     * set active status. (The circular sweep uses steps of
690     * approximately half the array size plus 1, to avoid bias
691     * stemming from leftmost packing of the array in ForkJoinPool.)
692 jsr166 1.1 *
693     * This method must be both fast and quiet -- usually avoiding
694     * memory accesses that could disrupt cache sharing etc other than
695 dl 1.14 * those needed to check for and take tasks (or to activate if not
696     * already active). This accounts for, among other things,
697     * updating random seed in place without storing it until exit.
698 jsr166 1.1 *
699     * @return a task, or null if none found
700     */
701     private ForkJoinTask<?> scan() {
702 dl 1.14 ForkJoinPool p = pool;
703 dl 1.16 ForkJoinWorkerThread[] ws; // worker array
704     int n; // upper bound of #workers
705     if ((ws = p.workers) != null && (n = ws.length) > 1) {
706     boolean canSteal = active; // shadow active status
707     int r = seed; // extract seed once
708     int mask = n - 1;
709     int j = -n; // loop counter
710     int k = r; // worker index, random if j < 0
711     for (;;) {
712     ForkJoinWorkerThread v = ws[k & mask];
713     r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // inline xorshift
714 dl 1.20 ForkJoinTask<?>[] q; ForkJoinTask<?> t; int b, a;
715     if (v != null && (b = v.base) != v.sp &&
716     (q = v.queue) != null) {
717     int i = (q.length - 1) & b;
718     long u = (i << qShift) + qBase; // raw offset
719     int pid = poolIndex;
720     if ((t = q[i]) != null) {
721     if (!canSteal && // inline p.tryIncrementActiveCount
722     UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
723     a = p.runState, a + 1))
724     canSteal = active = true;
725     if (canSteal && v.base == b++ &&
726 dl 1.18 UNSAFE.compareAndSwapObject(q, u, t, null)) {
727 dl 1.20 v.base = b;
728 dl 1.18 v.stealHint = pid;
729 dl 1.20 UNSAFE.putOrderedObject(this,
730     currentStealOffset, t);
731 dl 1.18 seed = r;
732     ++stealCount;
733     return t;
734 dl 1.17 }
735 jsr166 1.1 }
736 dl 1.16 j = -n;
737     k = r; // restart on contention
738 jsr166 1.1 }
739 dl 1.16 else if (++j <= 0)
740     k = r;
741     else if (j <= n)
742     k += (n >>> 1) | 1;
743     else
744     break;
745 jsr166 1.1 }
746 dl 1.14 }
747     return null;
748 jsr166 1.1 }
749    
750 dl 1.14 // Run State management
751    
752     // status check methods used mainly by ForkJoinPool
753 jsr166 1.33 final boolean isRunning() { return runState == 0; }
754     final boolean isTerminated() { return (runState & TERMINATED) != 0; }
755     final boolean isSuspended() { return (runState & SUSPENDED) != 0; }
756     final boolean isTrimmed() { return (runState & TRIMMED) != 0; }
757 dl 1.14
758 jsr166 1.31 final boolean isTerminating() {
759 dl 1.30 if ((runState & TERMINATING) != 0)
760     return true;
761     if (pool.isAtLeastTerminating()) { // propagate pool state
762     shutdown();
763     return true;
764     }
765     return false;
766     }
767    
768 jsr166 1.1 /**
769 dl 1.19 * Sets state to TERMINATING. Does NOT unpark or interrupt
770 dl 1.20 * to wake up if currently blocked. Callers must do so if desired.
771 dl 1.14 */
772 dl 1.19 final void shutdown() {
773 dl 1.14 for (;;) {
774     int s = runState;
775 dl 1.18 if ((s & (TERMINATING|TERMINATED)) != 0)
776     break;
777 dl 1.14 if ((s & SUSPENDED) != 0) { // kill and wakeup if suspended
778     if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
779     (s & ~SUSPENDED) |
780 dl 1.18 (TRIMMED|TERMINATING)))
781 dl 1.14 break;
782     }
783     else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
784     s | TERMINATING))
785     break;
786     }
787     }
788    
789     /**
790 jsr166 1.25 * Sets state to TERMINATED. Called only by onTermination().
791 dl 1.14 */
792     private void setTerminated() {
793     int s;
794     do {} while (!UNSAFE.compareAndSwapInt(this, runStateOffset,
795     s = runState,
796     s | (TERMINATING|TERMINATED)));
797     }
798    
799     /**
800 dl 1.19 * If suspended, tries to set status to unsuspended.
801 dl 1.20 * Does NOT wake up if blocked.
802 jsr166 1.1 *
803 dl 1.14 * @return true if successful
804 jsr166 1.1 */
805 dl 1.14 final boolean tryUnsuspend() {
806 dl 1.18 int s;
807     while (((s = runState) & SUSPENDED) != 0) {
808     if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
809     s & ~SUSPENDED))
810     return true;
811     }
812 dl 1.17 return false;
813 jsr166 1.1 }
814    
815     /**
816 dl 1.18 * Sets suspended status and blocks as spare until resumed
817     * or shutdown.
818 jsr166 1.1 */
819 dl 1.19 final void suspendAsSpare() {
820 dl 1.18 for (;;) { // set suspended unless terminating
821 dl 1.14 int s = runState;
822     if ((s & TERMINATING) != 0) { // must kill
823     if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
824     s | (TRIMMED | TERMINATING)))
825 dl 1.19 return;
826 dl 1.14 }
827     else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
828     s | SUSPENDED))
829     break;
830     }
831 dl 1.18 ForkJoinPool p = pool;
832     p.pushSpare(this);
833 dl 1.14 while ((runState & SUSPENDED) != 0) {
834 dl 1.19 if (p.tryAccumulateStealCount(this)) {
835     interrupted(); // clear/ignore interrupts
836 dl 1.18 if ((runState & SUSPENDED) == 0)
837     break;
838 dl 1.20 LockSupport.park(this);
839 dl 1.14 }
840 jsr166 1.1 }
841 dl 1.14 }
842    
843     // Misc support methods for ForkJoinPool
844    
845     /**
846     * Returns an estimate of the number of tasks in the queue. Also
847     * used by ForkJoinTask.
848     */
849     final int getQueueSize() {
850 dl 1.18 int n; // external calls must read base first
851     return (n = -base + sp) <= 0 ? 0 : n;
852 jsr166 1.1 }
853    
854 dl 1.14 /**
855 jsr166 1.1 * Removes and cancels all tasks in queue. Can be called from any
856     * thread.
857     */
858     final void cancelTasks() {
859 dl 1.18 ForkJoinTask<?> cj = currentJoin; // try to cancel ongoing tasks
860     if (cj != null) {
861     currentJoin = null;
862     cj.cancelIgnoringExceptions();
863     try {
864     this.interrupt(); // awaken wait
865     } catch (SecurityException ignore) {
866     }
867     }
868     ForkJoinTask<?> cs = currentSteal;
869     if (cs != null) {
870     currentSteal = null;
871     cs.cancelIgnoringExceptions();
872     }
873 dl 1.14 while (base != sp) {
874     ForkJoinTask<?> t = deqTask();
875     if (t != null)
876     t.cancelIgnoringExceptions();
877     }
878 jsr166 1.1 }
879    
880     /**
881     * Drains tasks to given collection c.
882     *
883     * @return the number of tasks drained
884     */
885 jsr166 1.5 final int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
886 jsr166 1.1 int n = 0;
887 dl 1.14 while (base != sp) {
888     ForkJoinTask<?> t = deqTask();
889     if (t != null) {
890     c.add(t);
891     ++n;
892     }
893 jsr166 1.1 }
894     return n;
895     }
896    
897 dl 1.14 // Support methods for ForkJoinTask
898    
899 jsr166 1.1 /**
900 dl 1.18 * Gets and removes a local task.
901     *
902     * @return a task, if available
903     */
904     final ForkJoinTask<?> pollLocalTask() {
905 dl 1.19 ForkJoinPool p = pool;
906 dl 1.18 while (sp != base) {
907 dl 1.19 int a; // inline p.tryIncrementActiveCount
908     if (active ||
909     (active = UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
910     a = p.runState, a + 1)))
911 jsr166 1.23 return locallyFifo ? locallyDeqTask() : popTask();
912 dl 1.18 }
913     return null;
914     }
915    
916     /**
917     * Gets and removes a local or stolen task.
918     *
919     * @return a task, if available
920     */
921     final ForkJoinTask<?> pollTask() {
922     ForkJoinTask<?> t = pollLocalTask();
923     if (t == null) {
924     t = scan();
925 dl 1.20 // cannot retain/track/help steal
926     UNSAFE.putOrderedObject(this, currentStealOffset, null);
927 dl 1.18 }
928     return t;
929     }
930    
931     /**
932 dl 1.17 * Possibly runs some tasks and/or blocks, until task is done.
933     *
934     * @param joinMe the task to join
935 dl 1.34 * @param timed true if use timed wait
936     * @param nanos wait time if timed
937 dl 1.17 */
938 dl 1.34 final void joinTask(ForkJoinTask<?> joinMe, boolean timed, long nanos) {
939 dl 1.18 // currentJoin only written by this thread; only need ordered store
940     ForkJoinTask<?> prevJoin = currentJoin;
941     UNSAFE.putOrderedObject(this, currentJoinOffset, joinMe);
942 dl 1.32 if (isTerminating()) // cancel if shutting down
943     joinMe.cancelIgnoringExceptions();
944 dl 1.38 else {
945     if (sp != base)
946     localHelpJoinTask(joinMe);
947     if (joinMe.status >= 0)
948     pool.awaitJoin(joinMe, this, timed, nanos);
949     }
950 dl 1.18 UNSAFE.putOrderedObject(this, currentJoinOffset, prevJoin);
951     }
952    
953     /**
954 dl 1.38 * Run tasks in local queue until given task is done.
955     * Not currently used because it complicates semantics.
956     *
957     * @param joinMe the task to join
958     */
959     private void localHelpJoinTask(ForkJoinTask<?> joinMe) {
960     int s;
961     ForkJoinTask<?>[] q;
962     while (joinMe.status >= 0 && (s = sp) != base && (q = queue) != null) {
963     int i = (q.length - 1) & --s;
964     long u = (i << qShift) + qBase; // raw offset
965     ForkJoinTask<?> t = q[i];
966     if (t == null) // lost to a stealer
967     break;
968     if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
969     /*
970     * This recheck (and similarly in helpJoinTask)
971     * handles cases where joinMe is independently
972     * cancelled or forced even though there is other work
973     * available. Back out of the pop by putting t back
974     * into slot before we commit by writing sp.
975     */
976     if (joinMe.status < 0) {
977     UNSAFE.putObjectVolatile(q, u, t);
978     break;
979     }
980     sp = s;
981     // UNSAFE.putOrderedInt(this, spOffset, s);
982     t.quietlyExec();
983     }
984     }
985     }
986    
987     /**
988 dl 1.32 * Tries to locate and help perform tasks for a stealer of the
989     * given task, or in turn one of its stealers. Traces
990     * currentSteal->currentJoin links looking for a thread working on
991     * a descendant of the given task and with a non-empty queue to
992     * steal back and execute tasks from.
993 dl 1.18 *
994 dl 1.20 * The implementation is very branchy to cope with potential
995 dl 1.18 * inconsistencies or loops encountering chains that are stale,
996     * unknown, or of length greater than MAX_HELP_DEPTH links. All
997     * of these cases are dealt with by just returning back to the
998     * caller, who is expected to retry if other join mechanisms also
999     * don't work out.
1000 dl 1.17 *
1001     * @param joinMe the task to join
1002     */
1003 dl 1.18 final void helpJoinTask(ForkJoinTask<?> joinMe) {
1004 dl 1.20 ForkJoinWorkerThread[] ws;
1005     int n;
1006     if (joinMe.status < 0) // already done
1007     return;
1008     if ((ws = pool.workers) == null || (n = ws.length) <= 1)
1009     return; // need at least 2 workers
1010    
1011     ForkJoinTask<?> task = joinMe; // base of chain
1012     ForkJoinWorkerThread thread = this; // thread with stolen task
1013     for (int d = 0; d < MAX_HELP_DEPTH; ++d) { // chain length
1014     // Try to find v, the stealer of task, by first using hint
1015     ForkJoinWorkerThread v = ws[thread.stealHint & (n - 1)];
1016     if (v == null || v.currentSteal != task) {
1017     for (int j = 0; ; ++j) { // search array
1018     if (j < n) {
1019     ForkJoinTask<?> vs;
1020 dl 1.38 if ((v = ws[j]) != null &&
1021     (v != this || base == sp) &&
1022 dl 1.20 (vs = v.currentSteal) != null) {
1023     if (joinMe.status < 0 || task.status < 0)
1024     return; // stale or done
1025     if (vs == task) {
1026     thread.stealHint = j;
1027     break; // save hint for next time
1028 dl 1.18 }
1029     }
1030 dl 1.17 }
1031 dl 1.20 else
1032     return; // no stealer
1033 dl 1.17 }
1034 dl 1.20 }
1035     for (;;) { // Try to help v, using specialized form of deqTask
1036     if (joinMe.status < 0)
1037     return;
1038     int b = v.base;
1039     ForkJoinTask<?>[] q = v.queue;
1040     if (b == v.sp || q == null)
1041     break;
1042     int i = (q.length - 1) & b;
1043     long u = (i << qShift) + qBase;
1044     ForkJoinTask<?> t = q[i];
1045     int pid = poolIndex;
1046     ForkJoinTask<?> ps = currentSteal;
1047     if (task.status < 0)
1048     return; // stale or done
1049     if (t != null && v.base == b++ &&
1050     UNSAFE.compareAndSwapObject(q, u, t, null)) {
1051     if (joinMe.status < 0) {
1052     UNSAFE.putObjectVolatile(q, u, t);
1053     return; // back out on cancel
1054 dl 1.17 }
1055 dl 1.20 v.base = b;
1056     v.stealHint = pid;
1057     UNSAFE.putOrderedObject(this, currentStealOffset, t);
1058     t.quietlyExec();
1059     UNSAFE.putOrderedObject(this, currentStealOffset, ps);
1060 dl 1.17 }
1061     }
1062 dl 1.20 // Try to descend to find v's stealer
1063     ForkJoinTask<?> next = v.currentJoin;
1064     if (task.status < 0 || next == null || next == task ||
1065     joinMe.status < 0)
1066     return;
1067     task = next;
1068     thread = v;
1069 dl 1.17 }
1070     }
1071    
1072     /**
1073 dl 1.29 * Implements ForkJoinTask.getSurplusQueuedTaskCount().
1074 dl 1.14 * Returns an estimate of the number of tasks, offset by a
1075     * function of number of idle workers.
1076     *
1077     * This method provides a cheap heuristic guide for task
1078     * partitioning when programmers, frameworks, tools, or languages
1079     * have little or no idea about task granularity. In essence by
1080     * offering this method, we ask users only about tradeoffs in
1081     * overhead vs expected throughput and its variance, rather than
1082     * how finely to partition tasks.
1083     *
1084     * In a steady state strict (tree-structured) computation, each
1085     * thread makes available for stealing enough tasks for other
1086     * threads to remain active. Inductively, if all threads play by
1087     * the same rules, each thread should make available only a
1088     * constant number of tasks.
1089     *
1090     * The minimum useful constant is just 1. But using a value of 1
1091     * would require immediate replenishment upon each steal to
1092     * maintain enough tasks, which is infeasible. Further,
1093     * partitionings/granularities of offered tasks should minimize
1094     * steal rates, which in general means that threads nearer the top
1095     * of computation tree should generate more than those nearer the
1096     * bottom. In perfect steady state, each thread is at
1097     * approximately the same level of computation tree. However,
1098     * producing extra tasks amortizes the uncertainty of progress and
1099     * diffusion assumptions.
1100     *
1101     * So, users will want to use values larger, but not much larger
1102     * than 1 to both smooth over transient shortages and hedge
1103     * against uneven progress; as traded off against the cost of
1104     * extra task overhead. We leave the user to pick a threshold
1105     * value to compare with the results of this call to guide
1106     * decisions, but recommend values such as 3.
1107     *
1108     * When all threads are active, it is on average OK to estimate
1109     * surplus strictly locally. In steady-state, if one thread is
1110     * maintaining say 2 surplus tasks, then so are others. So we can
1111     * just use estimated queue length (although note that (sp - base)
1112     * can be an overestimate because of stealers lagging increments
1113     * of base). However, this strategy alone leads to serious
1114     * mis-estimates in some non-steady-state conditions (ramp-up,
1115     * ramp-down, other stalls). We can detect many of these by
1116     * further considering the number of "idle" threads, that are
1117     * known to have zero queued tasks, so compensate by a factor of
1118     * (#idle/#active) threads.
1119 jsr166 1.1 */
1120 dl 1.14 final int getEstimatedSurplusTaskCount() {
1121     return sp - base - pool.idlePerActive();
1122 jsr166 1.1 }
1123    
1124     /**
1125     * Runs tasks until {@code pool.isQuiescent()}.
1126     */
1127     final void helpQuiescePool() {
1128 dl 1.20 ForkJoinTask<?> ps = currentSteal; // to restore below
1129 jsr166 1.1 for (;;) {
1130 dl 1.14 ForkJoinTask<?> t = pollLocalTask();
1131 dl 1.20 if (t != null || (t = scan()) != null)
1132 dl 1.18 t.quietlyExec();
1133 dl 1.14 else {
1134     ForkJoinPool p = pool;
1135 dl 1.19 int a; // to inline CASes
1136 dl 1.14 if (active) {
1137 dl 1.19 if (!UNSAFE.compareAndSwapInt
1138     (p, poolRunStateOffset, a = p.runState, a - 1))
1139 dl 1.18 continue; // retry later
1140 dl 1.14 active = false; // inactivate
1141 dl 1.20 UNSAFE.putOrderedObject(this, currentStealOffset, ps);
1142 dl 1.14 }
1143     if (p.isQuiescent()) {
1144     active = true; // re-activate
1145 jsr166 1.22 do {} while (!UNSAFE.compareAndSwapInt
1146     (p, poolRunStateOffset, a = p.runState, a+1));
1147 dl 1.14 return;
1148     }
1149     }
1150 jsr166 1.1 }
1151     }
1152    
1153     // Unsafe mechanics
1154    
1155     private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
1156 dl 1.18 private static final long spOffset =
1157     objectFieldOffset("sp", ForkJoinWorkerThread.class);
1158 jsr166 1.2 private static final long runStateOffset =
1159 jsr166 1.3 objectFieldOffset("runState", ForkJoinWorkerThread.class);
1160 dl 1.18 private static final long currentJoinOffset =
1161     objectFieldOffset("currentJoin", ForkJoinWorkerThread.class);
1162     private static final long currentStealOffset =
1163     objectFieldOffset("currentSteal", ForkJoinWorkerThread.class);
1164 dl 1.14 private static final long qBase =
1165     UNSAFE.arrayBaseOffset(ForkJoinTask[].class);
1166 dl 1.19 private static final long poolRunStateOffset = // to inline CAS
1167     objectFieldOffset("runState", ForkJoinPool.class);
1168 dl 1.18
1169 jsr166 1.2 private static final int qShift;
1170 jsr166 1.1
1171     static {
1172     int s = UNSAFE.arrayIndexScale(ForkJoinTask[].class);
1173     if ((s & (s-1)) != 0)
1174     throw new Error("data type scale not a power of two");
1175     qShift = 31 - Integer.numberOfLeadingZeros(s);
1176 dl 1.24 MAXIMUM_QUEUE_CAPACITY = 1 << (31 - qShift);
1177 jsr166 1.1 }
1178 jsr166 1.3
1179     private static long objectFieldOffset(String field, Class<?> klazz) {
1180     try {
1181     return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1182     } catch (NoSuchFieldException e) {
1183     // Convert Exception to corresponding Error
1184     NoSuchFieldError error = new NoSuchFieldError(field);
1185     error.initCause(e);
1186     throw error;
1187     }
1188     }
1189 jsr166 1.1 }