ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinWorkerThread.java
Revision: 1.4
Committed: Wed Jul 29 02:35:47 2009 UTC (14 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.3: +6 -5 lines
Log Message:
sync with jsr166y package

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.Collection;
10
11 /**
12 * A thread managed by a {@link ForkJoinPool}. This class is
13 * subclassable solely for the sake of adding functionality -- there
14 * are no overridable methods dealing with scheduling or
15 * execution. However, you can override initialization and termination
16 * methods surrounding the main task processing loop. If you do
17 * create such a subclass, you will also need to supply a custom
18 * ForkJoinWorkerThreadFactory to use it in a ForkJoinPool.
19 *
20 * @since 1.7
21 * @author Doug Lea
22 */
23 public class ForkJoinWorkerThread extends Thread {
24 /*
25 * Algorithm overview:
26 *
27 * 1. Work-Stealing: Work-stealing queues are special forms of
28 * Deques that support only three of the four possible
29 * end-operations -- push, pop, and deq (aka steal), and only do
30 * so under the constraints that push and pop are called only from
31 * the owning thread, while deq may be called from other threads.
32 * (If you are unfamiliar with them, you probably want to read
33 * Herlihy and Shavit's book "The Art of Multiprocessor
34 * programming", chapter 16 describing these in more detail before
35 * proceeding.) The main work-stealing queue design is roughly
36 * similar to "Dynamic Circular Work-Stealing Deque" by David
37 * Chase and Yossi Lev, SPAA 2005
38 * (http://research.sun.com/scalable/pubs/index.html). The main
39 * difference ultimately stems from gc requirements that we null
40 * out taken slots as soon as we can, to maintain as small a
41 * footprint as possible even in programs generating huge numbers
42 * of tasks. To accomplish this, we shift the CAS arbitrating pop
43 * vs deq (steal) from being on the indices ("base" and "sp") to
44 * the slots themselves (mainly via method "casSlotNull()"). So,
45 * both a successful pop and deq mainly entail CAS'ing a non-null
46 * slot to null. Because we rely on CASes of references, we do
47 * not need tag bits on base or sp. They are simple ints as used
48 * in any circular array-based queue (see for example ArrayDeque).
49 * Updates to the indices must still be ordered in a way that
50 * guarantees that (sp - base) > 0 means the queue is empty, but
51 * otherwise may err on the side of possibly making the queue
52 * appear nonempty when a push, pop, or deq have not fully
53 * committed. Note that this means that the deq operation,
54 * considered individually, is not wait-free. One thief cannot
55 * successfully continue until another in-progress one (or, if
56 * previously empty, a push) completes. However, in the
57 * aggregate, we ensure at least probabilistic non-blockingness. If
58 * an attempted steal fails, a thief always chooses a different
59 * random victim target to try next. So, in order for one thief to
60 * progress, it suffices for any in-progress deq or new push on
61 * any empty queue to complete. One reason this works well here is
62 * that apparently-nonempty often means soon-to-be-stealable,
63 * which gives threads a chance to activate if necessary before
64 * stealing (see below).
65 *
66 * Efficient implementation of this approach currently relies on
67 * an uncomfortable amount of "Unsafe" mechanics. To maintain
68 * correct orderings, reads and writes of variable base require
69 * volatile ordering. Variable sp does not require volatile write
70 * but needs cheaper store-ordering on writes. Because they are
71 * protected by volatile base reads, reads of the queue array and
72 * its slots do not need volatile load semantics, but writes (in
73 * push) require store order and CASes (in pop and deq) require
74 * (volatile) CAS semantics. Since these combinations aren't
75 * supported using ordinary volatiles, the only way to accomplish
76 * these efficiently is to use direct Unsafe calls. (Using external
77 * AtomicIntegers and AtomicReferenceArrays for the indices and
78 * array is significantly slower because of memory locality and
79 * indirection effects.) Further, performance on most platforms is
80 * very sensitive to placement and sizing of the (resizable) queue
81 * array. Even though these queues don't usually become all that
82 * big, the initial size must be large enough to counteract cache
83 * contention effects across multiple queues (especially in the
84 * presence of GC cardmarking). Also, to improve thread-locality,
85 * queues are currently initialized immediately after the thread
86 * gets the initial signal to start processing tasks. However,
87 * all queue-related methods except pushTask are written in a way
88 * that allows them to instead be lazily allocated and/or disposed
89 * of when empty. All together, these low-level implementation
90 * choices produce as much as a factor of 4 performance
91 * improvement compared to naive implementations, and enable the
92 * processing of billions of tasks per second, sometimes at the
93 * expense of ugliness.
94 *
95 * 2. Run control: The primary run control is based on a global
96 * counter (activeCount) held by the pool. It uses an algorithm
97 * similar to that in Herlihy and Shavit section 17.6 to cause
98 * threads to eventually block when all threads declare they are
99 * inactive. (See variable "scans".) For this to work, threads
100 * must be declared active when executing tasks, and before
101 * stealing a task. They must be inactive before blocking on the
102 * Pool Barrier (awaiting a new submission or other Pool
103 * event). In between, there is some free play which we take
104 * advantage of to avoid contention and rapid flickering of the
105 * global activeCount: If inactive, we activate only if a victim
106 * queue appears to be nonempty (see above). Similarly, a thread
107 * tries to inactivate only after a full scan of other threads.
108 * The net effect is that contention on activeCount is rarely a
109 * measurable performance issue. (There are also a few other cases
110 * where we scan for work rather than retry/block upon
111 * contention.)
112 *
113 * 3. Selection control. We maintain policy of always choosing to
114 * run local tasks rather than stealing, and always trying to
115 * steal tasks before trying to run a new submission. All steals
116 * are currently performed in randomly-chosen deq-order. It may be
117 * worthwhile to bias these with locality / anti-locality
118 * information, but doing this well probably requires more
119 * lower-level information from JVMs than currently provided.
120 */
121
122 /**
123 * Capacity of work-stealing queue array upon initialization.
124 * Must be a power of two. Initial size must be at least 2, but is
125 * padded to minimize cache effects.
126 */
127 private static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
128
129 /**
130 * Maximum work-stealing queue array size. Must be less than or
131 * equal to 1 << 28 to ensure lack of index wraparound. (This
132 * is less than usual bounds, because we need leftshift by 3
133 * to be in int range).
134 */
135 private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 28;
136
137 /**
138 * The pool this thread works in. Accessed directly by ForkJoinTask.
139 */
140 final ForkJoinPool pool;
141
142 /**
143 * The work-stealing queue array. Size must be a power of two.
144 * Initialized when thread starts, to improve memory locality.
145 */
146 private ForkJoinTask<?>[] queue;
147
148 /**
149 * Index (mod queue.length) of next queue slot to push to or pop
150 * from. It is written only by owner thread, via ordered store.
151 * Both sp and base are allowed to wrap around on overflow, but
152 * (sp - base) still estimates size.
153 */
154 private volatile int sp;
155
156 /**
157 * Index (mod queue.length) of least valid queue slot, which is
158 * always the next position to steal from if nonempty.
159 */
160 private volatile int base;
161
162 /**
163 * Activity status. When true, this worker is considered active.
164 * Must be false upon construction. It must be true when executing
165 * tasks, and BEFORE stealing a task. It must be false before
166 * calling pool.sync.
167 */
168 private boolean active;
169
170 /**
171 * Run state of this worker. Supports simple versions of the usual
172 * shutdown/shutdownNow control.
173 */
174 private volatile int runState;
175
176 /**
177 * Seed for random number generator for choosing steal victims.
178 * Uses Marsaglia xorshift. Must be nonzero upon initialization.
179 */
180 private int seed;
181
182 /**
183 * Number of steals, transferred to pool when idle
184 */
185 private int stealCount;
186
187 /**
188 * Index of this worker in pool array. Set once by pool before
189 * running, and accessed directly by pool during cleanup etc.
190 */
191 int poolIndex;
192
193 /**
194 * The last barrier event waited for. Accessed in pool callback
195 * methods, but only by current thread.
196 */
197 long lastEventCount;
198
199 /**
200 * True if use local fifo, not default lifo, for local polling
201 */
202 private boolean locallyFifo;
203
204 /**
205 * Creates a ForkJoinWorkerThread operating in the given pool.
206 *
207 * @param pool the pool this thread works in
208 * @throws NullPointerException if pool is null
209 */
210 protected ForkJoinWorkerThread(ForkJoinPool pool) {
211 if (pool == null) throw new NullPointerException();
212 this.pool = pool;
213 // Note: poolIndex is set by pool during construction
214 // Remaining initialization is deferred to onStart
215 }
216
217 // Public access methods
218
219 /**
220 * Returns the pool hosting this thread.
221 *
222 * @return the pool
223 */
224 public ForkJoinPool getPool() {
225 return pool;
226 }
227
228 /**
229 * Returns the index number of this thread in its pool. The
230 * returned value ranges from zero to the maximum number of
231 * threads (minus one) that have ever been created in the pool.
232 * This method may be useful for applications that track status or
233 * collect results per-worker rather than per-task.
234 *
235 * @return the index number
236 */
237 public int getPoolIndex() {
238 return poolIndex;
239 }
240
241 /**
242 * Establishes local first-in-first-out scheduling mode for forked
243 * tasks that are never joined.
244 *
245 * @param async if true, use locally FIFO scheduling
246 */
247 void setAsyncMode(boolean async) {
248 locallyFifo = async;
249 }
250
251 // Runstate management
252
253 // Runstate values. Order matters
254 private static final int RUNNING = 0;
255 private static final int SHUTDOWN = 1;
256 private static final int TERMINATING = 2;
257 private static final int TERMINATED = 3;
258
259 final boolean isShutdown() { return runState >= SHUTDOWN; }
260 final boolean isTerminating() { return runState >= TERMINATING; }
261 final boolean isTerminated() { return runState == TERMINATED; }
262 final boolean shutdown() { return transitionRunStateTo(SHUTDOWN); }
263 final boolean shutdownNow() { return transitionRunStateTo(TERMINATING); }
264
265 /**
266 * Transitions to at least the given state.
267 *
268 * @return {@code true} if not already at least at given state
269 */
270 private boolean transitionRunStateTo(int state) {
271 for (;;) {
272 int s = runState;
273 if (s >= state)
274 return false;
275 if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, state))
276 return true;
277 }
278 }
279
280 /**
281 * Tries to set status to active; fails on contention.
282 */
283 private boolean tryActivate() {
284 if (!active) {
285 if (!pool.tryIncrementActiveCount())
286 return false;
287 active = true;
288 }
289 return true;
290 }
291
292 /**
293 * Tries to set status to inactive; fails on contention.
294 */
295 private boolean tryInactivate() {
296 if (active) {
297 if (!pool.tryDecrementActiveCount())
298 return false;
299 active = false;
300 }
301 return true;
302 }
303
304 /**
305 * Computes next value for random victim probe. Scans don't
306 * require a very high quality generator, but also not a crummy
307 * one. Marsaglia xor-shift is cheap and works well.
308 */
309 private static int xorShift(int r) {
310 r ^= r << 1;
311 r ^= r >>> 3;
312 r ^= r << 10;
313 return r;
314 }
315
316 // Lifecycle methods
317
318 /**
319 * This method is required to be public, but should never be
320 * called explicitly. It performs the main run loop to execute
321 * ForkJoinTasks.
322 */
323 public void run() {
324 Throwable exception = null;
325 try {
326 onStart();
327 pool.sync(this); // await first pool event
328 mainLoop();
329 } catch (Throwable ex) {
330 exception = ex;
331 } finally {
332 onTermination(exception);
333 }
334 }
335
336 /**
337 * Executes tasks until shut down.
338 */
339 private void mainLoop() {
340 while (!isShutdown()) {
341 ForkJoinTask<?> t = pollTask();
342 if (t != null || (t = pollSubmission()) != null)
343 t.quietlyExec();
344 else if (tryInactivate())
345 pool.sync(this);
346 }
347 }
348
349 /**
350 * Initializes internal state after construction but before
351 * processing any tasks. If you override this method, you must
352 * invoke super.onStart() at the beginning of the method.
353 * 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 */
358 protected void onStart() {
359 // Allocate while starting to improve chances of thread-local
360 // isolation
361 queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
362 // Initial value of seed need not be especially random but
363 // should differ across workers and must be nonzero
364 int p = poolIndex + 1;
365 seed = p + (p << 8) + (p << 16) + (p << 24); // spread bits
366 }
367
368 /**
369 * Performs cleanup associated with termination of this worker
370 * thread. If you override this method, you must invoke
371 * {@code super.onTermination} at the end of the overridden method.
372 *
373 * @param exception the exception causing this thread to abort due
374 * to an unrecoverable error, or {@code null} if completed normally
375 */
376 protected void onTermination(Throwable exception) {
377 // Execute remaining local tasks unless aborting or terminating
378 while (exception == null && !pool.isTerminating() && base != sp) {
379 try {
380 ForkJoinTask<?> t = popTask();
381 if (t != null)
382 t.quietlyExec();
383 } catch (Throwable ex) {
384 exception = ex;
385 }
386 }
387 // Cancel other tasks, transition status, notify pool, and
388 // propagate exception to uncaught exception handler
389 try {
390 do {} while (!tryInactivate()); // ensure inactive
391 cancelTasks();
392 runState = TERMINATED;
393 pool.workerTerminated(this);
394 } catch (Throwable ex) { // Shouldn't ever happen
395 if (exception == null) // but if so, at least rethrown
396 exception = ex;
397 } finally {
398 if (exception != null)
399 ForkJoinTask.rethrowException(exception);
400 }
401 }
402
403 // Intrinsics-based support for queue operations.
404
405 /**
406 * Adds in store-order the given task at given slot of q to null.
407 * Caller must ensure q is non-null and index is in range.
408 */
409 private static void setSlot(ForkJoinTask<?>[] q, int i,
410 ForkJoinTask<?> t) {
411 UNSAFE.putOrderedObject(q, (i << qShift) + qBase, t);
412 }
413
414 /**
415 * CAS given slot of q to null. Caller must ensure q is non-null
416 * and index is in range.
417 */
418 private static boolean casSlotNull(ForkJoinTask<?>[] q, int i,
419 ForkJoinTask<?> t) {
420 return UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null);
421 }
422
423 /**
424 * Sets sp in store-order.
425 */
426 private void storeSp(int s) {
427 UNSAFE.putOrderedInt(this, spOffset, s);
428 }
429
430 // Main queue methods
431
432 /**
433 * Pushes a task. Called only by current thread.
434 *
435 * @param t the task. Caller must ensure non-null.
436 */
437 final void pushTask(ForkJoinTask<?> t) {
438 ForkJoinTask<?>[] q = queue;
439 int mask = q.length - 1;
440 int s = sp;
441 setSlot(q, s & mask, t);
442 storeSp(++s);
443 if ((s -= base) == 1)
444 pool.signalWork();
445 else if (s >= mask)
446 growQueue();
447 }
448
449 /**
450 * Tries to take a task from the base of the queue, failing if
451 * either empty or contended.
452 *
453 * @return a task, or null if none or contended
454 */
455 final ForkJoinTask<?> deqTask() {
456 ForkJoinTask<?> t;
457 ForkJoinTask<?>[] q;
458 int i;
459 int b;
460 if (sp != (b = base) &&
461 (q = queue) != null && // must read q after b
462 (t = q[i = (q.length - 1) & b]) != null &&
463 casSlotNull(q, i, t)) {
464 base = b + 1;
465 return t;
466 }
467 return null;
468 }
469
470 /**
471 * Returns a popped task, or null if empty. Ensures active status
472 * if non-null. Called only by current thread.
473 */
474 final ForkJoinTask<?> popTask() {
475 int s = sp;
476 while (s != base) {
477 if (tryActivate()) {
478 ForkJoinTask<?>[] q = queue;
479 int mask = q.length - 1;
480 int i = (s - 1) & mask;
481 ForkJoinTask<?> t = q[i];
482 if (t == null || !casSlotNull(q, i, t))
483 break;
484 storeSp(s - 1);
485 return t;
486 }
487 }
488 return null;
489 }
490
491 /**
492 * Specialized version of popTask to pop only if
493 * topmost element is the given task. Called only
494 * by current thread while active.
495 *
496 * @param t the task. Caller must ensure non-null.
497 */
498 final boolean unpushTask(ForkJoinTask<?> t) {
499 ForkJoinTask<?>[] q = queue;
500 int mask = q.length - 1;
501 int s = sp - 1;
502 if (casSlotNull(q, s & mask, t)) {
503 storeSp(s);
504 return true;
505 }
506 return false;
507 }
508
509 /**
510 * Returns next task.
511 */
512 final ForkJoinTask<?> peekTask() {
513 ForkJoinTask<?>[] q = queue;
514 if (q == null)
515 return null;
516 int mask = q.length - 1;
517 int i = locallyFifo ? base : (sp - 1);
518 return q[i & mask];
519 }
520
521 /**
522 * Doubles queue array size. Transfers elements by emulating
523 * steals (deqs) from old array and placing, oldest first, into
524 * new array.
525 */
526 private void growQueue() {
527 ForkJoinTask<?>[] oldQ = queue;
528 int oldSize = oldQ.length;
529 int newSize = oldSize << 1;
530 if (newSize > MAXIMUM_QUEUE_CAPACITY)
531 throw new RejectedExecutionException("Queue capacity exceeded");
532 ForkJoinTask<?>[] newQ = queue = new ForkJoinTask<?>[newSize];
533
534 int b = base;
535 int bf = b + oldSize;
536 int oldMask = oldSize - 1;
537 int newMask = newSize - 1;
538 do {
539 int oldIndex = b & oldMask;
540 ForkJoinTask<?> t = oldQ[oldIndex];
541 if (t != null && !casSlotNull(oldQ, oldIndex, t))
542 t = null;
543 setSlot(newQ, b & newMask, t);
544 } while (++b != bf);
545 pool.signalWork();
546 }
547
548 /**
549 * Tries to steal a task from another worker. Starts at a random
550 * index of workers array, and probes workers until finding one
551 * with non-empty queue or finding that all are empty. It
552 * randomly selects the first n probes. If these are empty, it
553 * resorts to a full circular traversal, which is necessary to
554 * accurately set active status by caller. Also restarts if pool
555 * events occurred since last scan, which forces refresh of
556 * workers array, in case barrier was associated with resize.
557 *
558 * This method must be both fast and quiet -- usually avoiding
559 * memory accesses that could disrupt cache sharing etc other than
560 * those needed to check for and take tasks. This accounts for,
561 * among other things, updating random seed in place without
562 * storing it until exit.
563 *
564 * @return a task, or null if none found
565 */
566 private ForkJoinTask<?> scan() {
567 ForkJoinTask<?> t = null;
568 int r = seed; // extract once to keep scan quiet
569 ForkJoinWorkerThread[] ws; // refreshed on outer loop
570 int mask; // must be power 2 minus 1 and > 0
571 outer:do {
572 if ((ws = pool.workers) != null && (mask = ws.length - 1) > 0) {
573 int idx = r;
574 int probes = ~mask; // use random index while negative
575 for (;;) {
576 r = xorShift(r); // update random seed
577 ForkJoinWorkerThread v = ws[mask & idx];
578 if (v == null || v.sp == v.base) {
579 if (probes <= mask)
580 idx = (probes++ < 0) ? r : (idx + 1);
581 else
582 break;
583 }
584 else if (!tryActivate() || (t = v.deqTask()) == null)
585 continue outer; // restart on contention
586 else
587 break outer;
588 }
589 }
590 } while (pool.hasNewSyncEvent(this)); // retry on pool events
591 seed = r;
592 return t;
593 }
594
595 /**
596 * Gets and removes a local or stolen task.
597 *
598 * @return a task, if available
599 */
600 final ForkJoinTask<?> pollTask() {
601 ForkJoinTask<?> t = locallyFifo ? deqTask() : popTask();
602 if (t == null && (t = scan()) != null)
603 ++stealCount;
604 return t;
605 }
606
607 /**
608 * Gets a local task.
609 *
610 * @return a task, if available
611 */
612 final ForkJoinTask<?> pollLocalTask() {
613 return locallyFifo ? deqTask() : popTask();
614 }
615
616 /**
617 * Returns a pool submission, if one exists, activating first.
618 *
619 * @return a submission, if available
620 */
621 private ForkJoinTask<?> pollSubmission() {
622 ForkJoinPool p = pool;
623 while (p.hasQueuedSubmissions()) {
624 ForkJoinTask<?> t;
625 if (tryActivate() && (t = p.pollSubmission()) != null)
626 return t;
627 }
628 return null;
629 }
630
631 // Methods accessed only by Pool
632
633 /**
634 * Removes and cancels all tasks in queue. Can be called from any
635 * thread.
636 */
637 final void cancelTasks() {
638 ForkJoinTask<?> t;
639 while (base != sp && (t = deqTask()) != null)
640 t.cancelIgnoringExceptions();
641 }
642
643 /**
644 * Drains tasks to given collection c.
645 *
646 * @return the number of tasks drained
647 */
648 final int drainTasksTo(Collection<ForkJoinTask<?>> c) {
649 int n = 0;
650 ForkJoinTask<?> t;
651 while (base != sp && (t = deqTask()) != null) {
652 c.add(t);
653 ++n;
654 }
655 return n;
656 }
657
658 /**
659 * Gets and clears steal count for accumulation by pool. Called
660 * only when known to be idle (in pool.sync and termination).
661 */
662 final int getAndClearStealCount() {
663 int sc = stealCount;
664 stealCount = 0;
665 return sc;
666 }
667
668 /**
669 * Returns {@code true} if at least one worker in the given array
670 * appears to have at least one queued task.
671 *
672 * @param ws array of workers
673 */
674 static boolean hasQueuedTasks(ForkJoinWorkerThread[] ws) {
675 if (ws != null) {
676 int len = ws.length;
677 for (int j = 0; j < 2; ++j) { // need two passes for clean sweep
678 for (int i = 0; i < len; ++i) {
679 ForkJoinWorkerThread w = ws[i];
680 if (w != null && w.sp != w.base)
681 return true;
682 }
683 }
684 }
685 return false;
686 }
687
688 // Support methods for ForkJoinTask
689
690 /**
691 * Returns an estimate of the number of tasks in the queue.
692 */
693 final int getQueueSize() {
694 // suppress momentarily negative values
695 return Math.max(0, sp - base);
696 }
697
698 /**
699 * Returns an estimate of the number of tasks, offset by a
700 * function of number of idle workers.
701 */
702 final int getEstimatedSurplusTaskCount() {
703 // The halving approximates weighting idle vs non-idle workers
704 return (sp - base) - (pool.getIdleThreadCount() >>> 1);
705 }
706
707 /**
708 * Scans, returning early if joinMe done.
709 */
710 final ForkJoinTask<?> scanWhileJoining(ForkJoinTask<?> joinMe) {
711 ForkJoinTask<?> t = pollTask();
712 if (t != null && joinMe.status < 0 && sp == base) {
713 pushTask(t); // unsteal if done and this task would be stealable
714 t = null;
715 }
716 return t;
717 }
718
719 /**
720 * Runs tasks until {@code pool.isQuiescent()}.
721 */
722 final void helpQuiescePool() {
723 for (;;) {
724 ForkJoinTask<?> t = pollTask();
725 if (t != null)
726 t.quietlyExec();
727 else if (tryInactivate() && pool.isQuiescent())
728 break;
729 }
730 do {} while (!tryActivate()); // re-activate on exit
731 }
732
733 // Unsafe mechanics
734
735 private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
736 private static final long spOffset =
737 objectFieldOffset("sp", ForkJoinWorkerThread.class);
738 private static final long runStateOffset =
739 objectFieldOffset("runState", ForkJoinWorkerThread.class);
740 private static final long qBase;
741 private static final int qShift;
742
743 static {
744 qBase = UNSAFE.arrayBaseOffset(ForkJoinTask[].class);
745 int s = UNSAFE.arrayIndexScale(ForkJoinTask[].class);
746 if ((s & (s-1)) != 0)
747 throw new Error("data type scale not a power of two");
748 qShift = 31 - Integer.numberOfLeadingZeros(s);
749 }
750
751 private static long objectFieldOffset(String field, Class<?> klazz) {
752 try {
753 return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
754 } catch (NoSuchFieldException e) {
755 // Convert Exception to corresponding Error
756 NoSuchFieldError error = new NoSuchFieldError(field);
757 error.initCause(e);
758 throw error;
759 }
760 }
761 }