1 |
dl |
1.3 |
/* |
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 |
jsr166 |
1.7 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
dl |
1.3 |
*/ |
6 |
|
|
|
7 |
jsr166 |
1.4 |
/* |
8 |
jsr166 |
1.5 |
* @test |
9 |
jsr166 |
1.8 |
* @bug 4949279 6937857 |
10 |
jsr166 |
1.4 |
* @summary Independent instantiations of Random() have distinct seeds. |
11 |
jsr166 |
1.8 |
* @key randomness |
12 |
jsr166 |
1.4 |
*/ |
13 |
dl |
1.3 |
|
14 |
jsr166 |
1.8 |
import java.util.ArrayList; |
15 |
|
|
import java.util.HashSet; |
16 |
|
|
import java.util.List; |
17 |
jsr166 |
1.1 |
import java.util.Random; |
18 |
|
|
|
19 |
|
|
public class DistinctSeeds { |
20 |
|
|
public static void main(String[] args) throws Exception { |
21 |
jsr166 |
1.6 |
// Strictly speaking, it is possible for these to randomly fail, |
22 |
jsr166 |
1.8 |
// but the probability should be small (approximately 2**-48). |
23 |
jsr166 |
1.6 |
if (new Random().nextLong() == new Random().nextLong() || |
24 |
|
|
new Random().nextLong() == new Random().nextLong()) |
25 |
jsr166 |
1.2 |
throw new RuntimeException("Random() seeds not unique."); |
26 |
jsr166 |
1.8 |
|
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 |
jsr166 |
1.1 |
} |
60 |
|
|
} |