ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/jtreg/util/Random/DistinctSeeds.java
(Generate patch)

Comparing jsr166/src/test/jtreg/util/Random/DistinctSeeds.java (file contents):
Revision 1.7 by jsr166, Tue Mar 15 19:47:04 2011 UTC vs.
Revision 1.8 by jsr166, Tue Sep 15 07:53:31 2015 UTC

# Line 6 | Line 6
6  
7   /*
8   * @test
9 < * @bug 4949279
9 > * @bug 4949279 6937857
10   * @summary Independent instantiations of Random() have distinct seeds.
11 + * @key randomness
12   */
13  
14 + import java.util.ArrayList;
15 + import java.util.HashSet;
16 + import java.util.List;
17   import java.util.Random;
18  
19   public class DistinctSeeds {
20      public static void main(String[] args) throws Exception {
21          // Strictly speaking, it is possible for these to randomly fail,
22 <        // but the probability should be *extremely* small (< 2**-63).
22 >        // but the probability should be small (approximately 2**-48).
23          if (new Random().nextLong() == new Random().nextLong() ||
24              new Random().nextLong() == new Random().nextLong())
25              throw new RuntimeException("Random() seeds not unique.");
26 +
27 +        // Now try generating seeds concurrently
28 +        class RandomCollector implements Runnable {
29 +            long[] randoms = new long[1<<17];
30 +            public void run() {
31 +                for (int i = 0; i < randoms.length; i++)
32 +                    randoms[i] = new Random().nextLong();
33 +            }
34 +        }
35 +        final int threadCount = 2;
36 +        List<RandomCollector> collectors = new ArrayList<>();
37 +        List<Thread> threads = new ArrayList<Thread>();
38 +        for (int i = 0; i < threadCount; i++) {
39 +            RandomCollector r = new RandomCollector();
40 +            collectors.add(r);
41 +            threads.add(new Thread(r));
42 +        }
43 +        for (Thread thread : threads)
44 +            thread.start();
45 +        for (Thread thread : threads)
46 +            thread.join();
47 +        int collisions = 0;
48 +        HashSet<Long> s = new HashSet<Long>();
49 +        for (RandomCollector r : collectors) {
50 +            for (long x : r.randoms) {
51 +                if (s.contains(x))
52 +                    collisions++;
53 +                s.add(x);
54 +            }
55 +        }
56 +        System.out.printf("collisions=%d%n", collisions);
57 +        if (collisions > 10)
58 +            throw new Error("too many collisions");
59      }
60   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines