ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinWorkerThread.java
Revision: 1.1
Committed: Sat Jul 25 01:06:20 2009 UTC (14 years, 10 months ago) by jsr166
Branch: MAIN
Log Message:
branch jsr166y into java.util.concurrent

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. Returns true if not
267 * already at least at given state.
268 */
269 private boolean transitionRunStateTo(int state) {
270 for (;;) {
271 int s = runState;
272 if (s >= state)
273 return false;
274 if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, state))
275 return true;
276 }
277 }
278
279 /**
280 * Tries to set status to active; fails on contention.
281 */
282 private boolean tryActivate() {
283 if (!active) {
284 if (!pool.tryIncrementActiveCount())
285 return false;
286 active = true;
287 }
288 return true;
289 }
290
291 /**
292 * Tries to set status to inactive; fails on contention.
293 */
294 private boolean tryInactivate() {
295 if (active) {
296 if (!pool.tryDecrementActiveCount())
297 return false;
298 active = false;
299 }
300 return true;
301 }
302
303 /**
304 * Computes next value for random victim probe. Scans don't
305 * require a very high quality generator, but also not a crummy
306 * one. Marsaglia xor-shift is cheap and works well.
307 */
308 private static int xorShift(int r) {
309 r ^= r << 1;
310 r ^= r >>> 3;
311 r ^= r << 10;
312 return r;
313 }
314
315 // Lifecycle methods
316
317 /**
318 * This method is required to be public, but should never be
319 * called explicitly. It performs the main run loop to execute
320 * ForkJoinTasks.
321 */
322 public void run() {
323 Throwable exception = null;
324 try {
325 onStart();
326 pool.sync(this); // await first pool event
327 mainLoop();
328 } catch (Throwable ex) {
329 exception = ex;
330 } finally {
331 onTermination(exception);
332 }
333 }
334
335 /**
336 * Executes tasks until shut down.
337 */
338 private void mainLoop() {
339 while (!isShutdown()) {
340 ForkJoinTask<?> t = pollTask();
341 if (t != null || (t = pollSubmission()) != null)
342 t.quietlyExec();
343 else if (tryInactivate())
344 pool.sync(this);
345 }
346 }
347
348 /**
349 * Initializes internal state after construction but before
350 * processing any tasks. If you override this method, you must
351 * invoke super.onStart() at the beginning of the method.
352 * Initialization requires care: Most fields must have legal
353 * default values, to ensure that attempted accesses from other
354 * threads work correctly even before this thread starts
355 * processing tasks.
356 */
357 protected void onStart() {
358 // Allocate while starting to improve chances of thread-local
359 // isolation
360 queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
361 // Initial value of seed need not be especially random but
362 // should differ across workers and must be nonzero
363 int p = poolIndex + 1;
364 seed = p + (p << 8) + (p << 16) + (p << 24); // spread bits
365 }
366
367 /**
368 * Performs cleanup associated with termination of this worker
369 * thread. If you override this method, you must invoke
370 * {@code super.onTermination} at the end of the overridden method.
371 *
372 * @param exception the exception causing this thread to abort due
373 * to an unrecoverable error, or null if completed normally
374 */
375 protected void onTermination(Throwable exception) {
376 // Execute remaining local tasks unless aborting or terminating
377 while (exception == null && !pool.isTerminating() && base != sp) {
378 try {
379 ForkJoinTask<?> t = popTask();
380 if (t != null)
381 t.quietlyExec();
382 } catch (Throwable ex) {
383 exception = ex;
384 }
385 }
386 // Cancel other tasks, transition status, notify pool, and
387 // propagate exception to uncaught exception handler
388 try {
389 do {} while (!tryInactivate()); // ensure inactive
390 cancelTasks();
391 runState = TERMINATED;
392 pool.workerTerminated(this);
393 } catch (Throwable ex) { // Shouldn't ever happen
394 if (exception == null) // but if so, at least rethrown
395 exception = ex;
396 } finally {
397 if (exception != null)
398 ForkJoinTask.rethrowException(exception);
399 }
400 }
401
402 // Intrinsics-based support for queue operations.
403
404 /**
405 * Adds in store-order the given task at given slot of q to null.
406 * Caller must ensure q is non-null and index is in range.
407 */
408 private static void setSlot(ForkJoinTask<?>[] q, int i,
409 ForkJoinTask<?> t) {
410 UNSAFE.putOrderedObject(q, (i << qShift) + qBase, t);
411 }
412
413 /**
414 * CAS given slot of q to null. Caller must ensure q is non-null
415 * and index is in range.
416 */
417 private static boolean casSlotNull(ForkJoinTask<?>[] q, int i,
418 ForkJoinTask<?> t) {
419 return UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null);
420 }
421
422 /**
423 * Sets sp in store-order.
424 */
425 private void storeSp(int s) {
426 UNSAFE.putOrderedInt(this, spOffset, s);
427 }
428
429 // Main queue methods
430
431 /**
432 * Pushes a task. Called only by current thread.
433 *
434 * @param t the task. Caller must ensure non-null.
435 */
436 final void pushTask(ForkJoinTask<?> t) {
437 ForkJoinTask<?>[] q = queue;
438 int mask = q.length - 1;
439 int s = sp;
440 setSlot(q, s & mask, t);
441 storeSp(++s);
442 if ((s -= base) == 1)
443 pool.signalWork();
444 else if (s >= mask)
445 growQueue();
446 }
447
448 /**
449 * Tries to take a task from the base of the queue, failing if
450 * either empty or contended.
451 *
452 * @return a task, or null if none or contended
453 */
454 final ForkJoinTask<?> deqTask() {
455 ForkJoinTask<?> t;
456 ForkJoinTask<?>[] q;
457 int i;
458 int b;
459 if (sp != (b = base) &&
460 (q = queue) != null && // must read q after b
461 (t = q[i = (q.length - 1) & b]) != null &&
462 casSlotNull(q, i, t)) {
463 base = b + 1;
464 return t;
465 }
466 return null;
467 }
468
469 /**
470 * Returns a popped task, or null if empty. Ensures active status
471 * if non-null. Called only by current thread.
472 */
473 final ForkJoinTask<?> popTask() {
474 int s = sp;
475 while (s != base) {
476 if (tryActivate()) {
477 ForkJoinTask<?>[] q = queue;
478 int mask = q.length - 1;
479 int i = (s - 1) & mask;
480 ForkJoinTask<?> t = q[i];
481 if (t == null || !casSlotNull(q, i, t))
482 break;
483 storeSp(s - 1);
484 return t;
485 }
486 }
487 return null;
488 }
489
490 /**
491 * Specialized version of popTask to pop only if
492 * topmost element is the given task. Called only
493 * by current thread while active.
494 *
495 * @param t the task. Caller must ensure non-null.
496 */
497 final boolean unpushTask(ForkJoinTask<?> t) {
498 ForkJoinTask<?>[] q = queue;
499 int mask = q.length - 1;
500 int s = sp - 1;
501 if (casSlotNull(q, s & mask, t)) {
502 storeSp(s);
503 return true;
504 }
505 return false;
506 }
507
508 /**
509 * Returns next task.
510 */
511 final ForkJoinTask<?> peekTask() {
512 ForkJoinTask<?>[] q = queue;
513 if (q == null)
514 return null;
515 int mask = q.length - 1;
516 int i = locallyFifo ? base : (sp - 1);
517 return q[i & mask];
518 }
519
520 /**
521 * Doubles queue array size. Transfers elements by emulating
522 * steals (deqs) from old array and placing, oldest first, into
523 * new array.
524 */
525 private void growQueue() {
526 ForkJoinTask<?>[] oldQ = queue;
527 int oldSize = oldQ.length;
528 int newSize = oldSize << 1;
529 if (newSize > MAXIMUM_QUEUE_CAPACITY)
530 throw new RejectedExecutionException("Queue capacity exceeded");
531 ForkJoinTask<?>[] newQ = queue = new ForkJoinTask<?>[newSize];
532
533 int b = base;
534 int bf = b + oldSize;
535 int oldMask = oldSize - 1;
536 int newMask = newSize - 1;
537 do {
538 int oldIndex = b & oldMask;
539 ForkJoinTask<?> t = oldQ[oldIndex];
540 if (t != null && !casSlotNull(oldQ, oldIndex, t))
541 t = null;
542 setSlot(newQ, b & newMask, t);
543 } while (++b != bf);
544 pool.signalWork();
545 }
546
547 /**
548 * Tries to steal a task from another worker. Starts at a random
549 * index of workers array, and probes workers until finding one
550 * with non-empty queue or finding that all are empty. It
551 * randomly selects the first n probes. If these are empty, it
552 * resorts to a full circular traversal, which is necessary to
553 * accurately set active status by caller. Also restarts if pool
554 * events occurred since last scan, which forces refresh of
555 * workers array, in case barrier was associated with resize.
556 *
557 * This method must be both fast and quiet -- usually avoiding
558 * memory accesses that could disrupt cache sharing etc other than
559 * those needed to check for and take tasks. This accounts for,
560 * among other things, updating random seed in place without
561 * storing it until exit.
562 *
563 * @return a task, or null if none found
564 */
565 private ForkJoinTask<?> scan() {
566 ForkJoinTask<?> t = null;
567 int r = seed; // extract once to keep scan quiet
568 ForkJoinWorkerThread[] ws; // refreshed on outer loop
569 int mask; // must be power 2 minus 1 and > 0
570 outer:do {
571 if ((ws = pool.workers) != null && (mask = ws.length - 1) > 0) {
572 int idx = r;
573 int probes = ~mask; // use random index while negative
574 for (;;) {
575 r = xorShift(r); // update random seed
576 ForkJoinWorkerThread v = ws[mask & idx];
577 if (v == null || v.sp == v.base) {
578 if (probes <= mask)
579 idx = (probes++ < 0) ? r : (idx + 1);
580 else
581 break;
582 }
583 else if (!tryActivate() || (t = v.deqTask()) == null)
584 continue outer; // restart on contention
585 else
586 break outer;
587 }
588 }
589 } while (pool.hasNewSyncEvent(this)); // retry on pool events
590 seed = r;
591 return t;
592 }
593
594 /**
595 * Gets and removes a local or stolen task.
596 *
597 * @return a task, if available
598 */
599 final ForkJoinTask<?> pollTask() {
600 ForkJoinTask<?> t = locallyFifo ? deqTask() : popTask();
601 if (t == null && (t = scan()) != null)
602 ++stealCount;
603 return t;
604 }
605
606 /**
607 * Gets a local task.
608 *
609 * @return a task, if available
610 */
611 final ForkJoinTask<?> pollLocalTask() {
612 return locallyFifo ? deqTask() : popTask();
613 }
614
615 /**
616 * Returns a pool submission, if one exists, activating first.
617 *
618 * @return a submission, if available
619 */
620 private ForkJoinTask<?> pollSubmission() {
621 ForkJoinPool p = pool;
622 while (p.hasQueuedSubmissions()) {
623 ForkJoinTask<?> t;
624 if (tryActivate() && (t = p.pollSubmission()) != null)
625 return t;
626 }
627 return null;
628 }
629
630 // Methods accessed only by Pool
631
632 /**
633 * Removes and cancels all tasks in queue. Can be called from any
634 * thread.
635 */
636 final void cancelTasks() {
637 ForkJoinTask<?> t;
638 while (base != sp && (t = deqTask()) != null)
639 t.cancelIgnoringExceptions();
640 }
641
642 /**
643 * Drains tasks to given collection c.
644 *
645 * @return the number of tasks drained
646 */
647 final int drainTasksTo(Collection<ForkJoinTask<?>> c) {
648 int n = 0;
649 ForkJoinTask<?> t;
650 while (base != sp && (t = deqTask()) != null) {
651 c.add(t);
652 ++n;
653 }
654 return n;
655 }
656
657 /**
658 * Gets and clears steal count for accumulation by pool. Called
659 * only when known to be idle (in pool.sync and termination).
660 */
661 final int getAndClearStealCount() {
662 int sc = stealCount;
663 stealCount = 0;
664 return sc;
665 }
666
667 /**
668 * Returns true if at least one worker in the given array appears
669 * to have at least one queued task.
670 *
671 * @param ws array of workers
672 */
673 static boolean hasQueuedTasks(ForkJoinWorkerThread[] ws) {
674 if (ws != null) {
675 int len = ws.length;
676 for (int j = 0; j < 2; ++j) { // need two passes for clean sweep
677 for (int i = 0; i < len; ++i) {
678 ForkJoinWorkerThread w = ws[i];
679 if (w != null && w.sp != w.base)
680 return true;
681 }
682 }
683 }
684 return false;
685 }
686
687 // Support methods for ForkJoinTask
688
689 /**
690 * Returns an estimate of the number of tasks in the queue.
691 */
692 final int getQueueSize() {
693 // suppress momentarily negative values
694 return Math.max(0, sp - base);
695 }
696
697 /**
698 * Returns an estimate of the number of tasks, offset by a
699 * function of number of idle workers.
700 */
701 final int getEstimatedSurplusTaskCount() {
702 // The halving approximates weighting idle vs non-idle workers
703 return (sp - base) - (pool.getIdleThreadCount() >>> 1);
704 }
705
706 /**
707 * Scans, returning early if joinMe done.
708 */
709 final ForkJoinTask<?> scanWhileJoining(ForkJoinTask<?> joinMe) {
710 ForkJoinTask<?> t = pollTask();
711 if (t != null && joinMe.status < 0 && sp == base) {
712 pushTask(t); // unsteal if done and this task would be stealable
713 t = null;
714 }
715 return t;
716 }
717
718 /**
719 * Runs tasks until {@code pool.isQuiescent()}.
720 */
721 final void helpQuiescePool() {
722 for (;;) {
723 ForkJoinTask<?> t = pollTask();
724 if (t != null)
725 t.quietlyExec();
726 else if (tryInactivate() && pool.isQuiescent())
727 break;
728 }
729 do {} while (!tryActivate()); // re-activate on exit
730 }
731
732 // Unsafe mechanics
733 private static long fieldOffset(String fieldName, Class<?> klazz) {
734 try {
735 return UNSAFE.objectFieldOffset(klazz.getDeclaredField(fieldName));
736 } catch (NoSuchFieldException e) {
737 // Convert Exception to Error
738 NoSuchFieldError error = new NoSuchFieldError(fieldName);
739 error.initCause(e);
740 throw error;
741 }
742 }
743
744 private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
745 static final long baseOffset =
746 fieldOffset("base", ForkJoinWorkerThread.class);
747 static final long spOffset =
748 fieldOffset("sp", ForkJoinWorkerThread.class);
749 static final long runStateOffset =
750 fieldOffset("runState", ForkJoinWorkerThread.class);
751 static final long qBase;
752 static final int qShift;
753
754 static {
755 qBase = UNSAFE.arrayBaseOffset(ForkJoinTask[].class);
756 int s = UNSAFE.arrayIndexScale(ForkJoinTask[].class);
757 if ((s & (s-1)) != 0)
758 throw new Error("data type scale not a power of two");
759 qShift = 31 - Integer.numberOfLeadingZeros(s);
760 }
761 }