ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinWorkerThread.java
Revision: 1.18
Committed: Sat Jul 25 00:34:00 2009 UTC (14 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.17: +3 -3 lines
Log Message:
Avoid wildcard imports

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