1 |
< |
/** |
2 |
< |
* @test 1.1 03/11/06 |
3 |
< |
* @bug 4949279 |
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 be equal, |
22 |
< |
// but the likelihood should be *extremely* small. |
23 |
< |
if (new Random().nextLong() == new Random().nextLong()) |
24 |
< |
throw new RuntimeException("Random seeds not unique."); |
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 |
|
} |