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).