The following code should create two Random objects with identical seeds:
System.out.println("System time before: " + System.currentTimeMillis());
Random r1 = new Random();
Random r2 = new Random(System.currentTimeMillis());
System.out.println("System time after: " + System.currentTimeMillis());
System.out.println("r1: " + r1.nextInt());
System.out.println("r2: " + r2.nextInt());
The seeds should be identical since System.currentTimeMillis() did not change before and after creating the two objects as shown in the output:
System time before: 1331889186449
System time after: 1331889186449
r1: -1836225474
r2: 2070673752
From the docs, the constructor without any arguments is simply:
public Random() { this(System.currentTimeMillis()); }
So what gives? Can anyone explain why the two generators return different outputs when they should have the same seed?
If you are using java.util.Random, this is the default no-args constructor I see – now it might depend on the version of JDK you are using (this code seems to be used for sun JDK 6 & 7 at least):
And just to confirm it, here is a code to check if the seeds are identical: