[50abab9] | 1 | public class JavaThread { |
---|
[be53b87] | 2 | // Simplistic low-quality Marsaglia Shift-XOR pseudo-random number generator. |
---|
| 3 | // Bijective |
---|
| 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. |
---|
| 7 | static volatile int Ticket = 0 ; |
---|
| 8 | |
---|
| 9 | private static int nextRandom (int x) { |
---|
| 10 | if (x == 0) { |
---|
| 11 | // reseed the PRNG |
---|
| 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 ; |
---|
| 20 | } |
---|
| 21 | x ^= x << 6; |
---|
| 22 | x ^= x >>> 21; |
---|
| 23 | x ^= x << 7; |
---|
| 24 | return x ; |
---|
| 25 | } |
---|
| 26 | static int x = 2; |
---|
| 27 | |
---|
[b4107c8] | 28 | static private int times = Integer.parseInt("10000") ; |
---|
[be53b87] | 29 | |
---|
[50abab9] | 30 | public static class MyThread extends Thread { |
---|
| 31 | @Override |
---|
| 32 | public void run() {} |
---|
| 33 | } |
---|
[be53b87] | 34 | public static void helper() throws InterruptedException { |
---|
[6e540ea] | 35 | for(int i = 1; i <= times; i += 1) { |
---|
[be53b87] | 36 | MyThread m = new MyThread(); |
---|
| 37 | x = nextRandom( x ); |
---|
| 38 | m.start(); |
---|
[50abab9] | 39 | m.join(); |
---|
| 40 | } |
---|
[be53b87] | 41 | } |
---|
| 42 | public static void InnerMain() throws InterruptedException { |
---|
| 43 | long start = System.nanoTime(); |
---|
| 44 | helper(); |
---|
[50abab9] | 45 | long end = System.nanoTime(); |
---|
[6e540ea] | 46 | System.out.println( (end - start) / times ); |
---|
[be53b87] | 47 | } |
---|
| 48 | public static void main(String[] args) throws InterruptedException { |
---|
[b4107c8] | 49 | if ( args.length > 2 ) System.exit( 1 ); |
---|
| 50 | if ( args.length == 2 ) { times = Integer.parseInt(args[1]); } |
---|
| 51 | |
---|
| 52 | for (int i = Integer.parseInt("5"); --i >= 0 ; ) { |
---|
[be53b87] | 53 | InnerMain(); |
---|
[6e540ea] | 54 | Thread.sleep(2000); // 2 seconds |
---|
[be53b87] | 55 | x = nextRandom(x); |
---|
| 56 | } |
---|
| 57 | if ( x == 0 ) System.out.println(x); |
---|
[50abab9] | 58 | } |
---|
[be53b87] | 59 | } |
---|
[b4107c8] | 60 | |
---|
| 61 | // Local Variables: // |
---|
| 62 | // tab-width: 4 // |
---|
| 63 | // End: // |
---|