I’m writing a class constructor with a decimal field, that is need to be initialized by a random value. Just one little field and I need to create new Random object. In the first place it looks cumbersome, and in the second there is can arise a lot of equal values, in case of creating a lot of objects in one time slice (new Random() is euqal to new Random(System.currentTimeMillis()), and equal timeMillis entails equal random values).
What is the best way to avoid this?
No, it’s not. In recent JDKs, it’s
new Random(seedUniquifier() ^ System.nanoTime());where seedUniquifier() is based on running a linear congruential generator on a static
AtomicLong. So it’s actually perfectly safe to createRandomobjects as needed.Of course, you can always have a
private static Randomfield and use that in the constructor.