Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get random value without creating `Random` object

Tags:

java

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?

like image 697
Nelson Tatius Avatar asked Apr 11 '12 20:04

Nelson Tatius


1 Answers

new Random() is euqal to new Random(System.currentTimeMillis())

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 create Random objects as needed.

Of course, you can always have a private static Random field and use that in the constructor.

like image 196
Michael Borgwardt Avatar answered Oct 05 '22 11:10

Michael Borgwardt