From a254d20e0e5ec936f6bf7ebee4a86322094db247 Mon Sep 17 00:00:00 2001 From: Joel Dice Date: Tue, 14 Feb 2012 13:01:00 -0700 Subject: [PATCH] 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. --- classpath/java/util/Random.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/classpath/java/util/Random.java b/classpath/java/util/Random.java index 856f30424a..311230f538 100644 --- a/classpath/java/util/Random.java +++ b/classpath/java/util/Random.java @@ -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) {