Nelson Tatius
Nelson Tatius

Reputation: 8043

Get random value without creating `Random` object

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?

Upvotes: 5

Views: 1508

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1499800

Are you're using Java 7, Random is thread-safe, as documented:

Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs.

So you can just use:

private static final Random random = new Random();

... or use ThreadLocalRandom if you're going to be using this from many threads. It's still not going to be as random as SecureRandom of course. Basically adjust your choice according to your needs.

Upvotes: 2

Adam Mihalcin
Adam Mihalcin

Reputation: 14458

You're looking for Math.random. This is a static method that implicitly initializes a new Random object the first time it is called, and then uses that object thereafter. So you get the benefits of sharing a single Random object between all the static field initializations, without having to manage a Random object yourself.

Upvotes: 6

Michael Borgwardt
Michael Borgwardt

Reputation: 346260

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.

Upvotes: 9

Related Questions