[50abab9] | 1 | public class JavaThread { |
---|
[be53b87] | 2 | // Simplistic low-quality Marsaglia Shift-XOR pseudo-random number generator. |
---|
[2a658e9] | 3 | // Bijective |
---|
[be53b87] | 4 | // Cycle length for non-zero values is 4G-1. |
---|
| 5 | // 0 is absorbing and should be avoided -- fixed point. |
---|
| 6 | // The returned value is typically masked to produce a positive value. |
---|
[2a658e9] | 7 | static volatile int Ticket = 0 ; |
---|
[be53b87] | 8 | |
---|
| 9 | private static int nextRandom (int x) { |
---|
[2a658e9] | 10 | if (x == 0) { |
---|
[be53b87] | 11 | // reseed the PRNG |
---|
[2a658e9] | 12 | // Ticket is accessed infrequently and does not constitute a coherence hot-spot. |
---|
| 13 | // Note that we use a non-atomic racy increment -- the race is rare and benign. |
---|
| 14 | // If the race is a concern switch to an AtomicInteger. |
---|
| 15 | // In addition accesses to the RW volatile global "Ticket" variable are not |
---|
| 16 | // (readily) predictable at compile-time so the JIT will not be able to elide |
---|
| 17 | // nextRandom() invocations. |
---|
| 18 | x = ++Ticket ; |
---|
| 19 | if (x == 0) x = 1 ; |
---|
[be53b87] | 20 | } |
---|
| 21 | x ^= x << 6; |
---|
| 22 | x ^= x >>> 21; |
---|
| 23 | x ^= x << 7; |
---|
[2a658e9] | 24 | return x ; |
---|
[be53b87] | 25 | } |
---|
| 26 | static int x = 2; |
---|
| 27 | |
---|
[2a658e9] | 28 | static private long times = Long.parseLong("100000"); |
---|
[be53b87] | 29 | |
---|
| 30 | public static void helper() { |
---|
[2a658e9] | 31 | for(long i = 1; i <= times; i += 1) { |
---|
[50abab9] | 32 | Thread.yield(); |
---|
| 33 | } |
---|
[be53b87] | 34 | } |
---|
| 35 | public static void InnerMain() { |
---|
| 36 | long start = System.nanoTime(); |
---|
| 37 | helper(); |
---|
[50abab9] | 38 | long end = System.nanoTime(); |
---|
[b4107c8] | 39 | System.out.println( (end - start) / times ); |
---|
[be53b87] | 40 | } |
---|
| 41 | public static void main(String[] args) throws InterruptedException { |
---|
[2c3562d] | 42 | if ( args.length > 1 ) System.exit( 1 ); |
---|
| 43 | if ( args.length == 1 ) { times = Long.parseLong(args[0]); } |
---|
[b4107c8] | 44 | |
---|
| 45 | for (int i = Integer.parseInt("5"); --i >= 0 ; ) { |
---|
[be53b87] | 46 | InnerMain(); |
---|
[b4107c8] | 47 | Thread.sleep(2000); // 2 seconds |
---|
[be53b87] | 48 | x = nextRandom(x); |
---|
| 49 | } |
---|
| 50 | if ( x == 0 ) System.out.println(x); |
---|
[50abab9] | 51 | } |
---|
[be53b87] | 52 | } |
---|
[b4107c8] | 53 | |
---|
| 54 | // Local Variables: // |
---|
| 55 | // tab-width: 4 // |
---|
| 56 | // End: // |
---|