Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferred way to use the random class

Tags:

java

random

What is the preferred way to use the Random class in Java ?

a) Create one object of Random and use it many times

b) Create a new object of Random each time a random value is needed

What are the drawbacks and beneftis ?

like image 549
John Threepwood Avatar asked Jan 15 '23 22:01

John Threepwood


1 Answers

Technically, the guarantee made by the class is that a single instance will produce a pseudorandom stream of values. With your method (b), there's no explicit guarantee that the resulting stream of values would meet the same statistical definition of randomness. So if you care about true statistical randomness, (a) would be preferred.

I don't see much benefit to (b). I suppose it means you don't need to hold onto a reference to a single instance of Random, but doing that in a singleton class would be straightforward. Generally I would be wary of creating lots of new objects for performance reasons, but you could measure the impact and decide whether it was acceptable.

So between these options I would usually prefer (a).

I can see a third option, of using more than one long-lived instance. You might do that if you have multiple threads and you want each to use its own Random object. (It's unclear to me from the javadoc what the implication are of having multiple threads calling a single object might be.)

like image 58
Dave Costa Avatar answered Jan 25 '23 18:01

Dave Costa