improve seed generation in java.util.Random

The previous code caused frequent seed collisions for successive calls
to the no-arg constructor, even for single threaded workloads.  This
patch should avoid such collisions in both single and multi-threaded
cases.
This commit is contained in:
Joel Dice 2012-02-14 13:01:00 -07:00
parent a1c5cccd96
commit a254d20e0e

View File

@ -13,7 +13,9 @@ package java.util;
public class Random {
private static final long Mask = 0x5DEECE66DL;
private static long nextSeed = 0;
private static final long InitialSeed = 123456789987654321L;
private static long nextSeed = InitialSeed;
private long seed;
@ -22,7 +24,13 @@ public class Random {
}
public Random() {
setSeed((nextSeed++) ^ System.currentTimeMillis());
synchronized (Random.class) {
setSeed(nextSeed ^ System.currentTimeMillis());
nextSeed *= 123456789987654321L;
if (nextSeed == 0) {
nextSeed = InitialSeed;
}
}
}
public void setSeed(long seed) {