The title pretty much sums it up. I have seen people construct an instance of Random globally, and use it in all of their code, and I have also seen people that construct an instance everytime they want to use Random.
My question is: When, if ever, should I construct a new instance of Random for generating random numbers?
Math.random() stores a Random instance in a RandomNumberGeneratorHolder, and calls it every time Math.random() is called.
My view: I should use a global Random() instance, because:
I can't think of any more reasons, but if I should use a global Random instance, I can imagine java developers implementing Random with at instance field, in addition to the constructor for special cases. That tells me that I am wrong. Should I use a global Random instance?
You should use a global Random
instance for performance reasons, instead of initializing one each time - see also API.
Please note that:
ThreadLocalRandom.current().next...
for each call (see official recommendation on the matter).In a single threaded program it's okay to use a single Random
object for the duration of the program.
In a multi-threaded program it's required that threads don't share a single Random
object. One way to achieve this is to use ThreadLocalRandom
or ThreadLocal
and Random
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With