ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/jtreg/util/Random/DistinctSeeds.java
Revision: 1.9
Committed: Wed Jan 4 04:46:19 2017 UTC (7 years, 3 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.8: +2 -2 lines
Log Message:
convert to Diamond

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/publicdomain/zero/1.0/
5 */
6
7 /*
8 * @test
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 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<>();
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<>();
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 }