So the answer by, Scary Wombat, on this question, he states that we should keep the created Random object as a field rather than in the method but I have seen many times online where similar methods are static. So my question is, why is it a practice to make similar methods static even though the method is using an instance variable - which in this case is Random?
-
2I think you're misunderstanding. If the `Random` was added as an instance variable, the method calling it *could not be static*. Either the method would be made non-static, or the field would be static. – resueman Nov 19 '15 at 14:58
-
Please also read the comments "`Random rand = new Random();` I would go so far as to say that it must be a field. Random objects created within a short time of each other will tend to produce similar output. So many calls to randInt within a short period of time will not give evenly distributed output." – Aurand Thus this means, recreating the `Random` object over and over again. Then the numbers generating by the `Random` objects are not random anymore. – martijnn2008 Nov 19 '15 at 15:01
2 Answers
If the method is static you cannot use that instance variable, as Scary Wombat explains in his answer Random objects created in a short period of time will produce PRNs that are not evenly distributed(as much as they can be). For this reason if you store the Random object as an instance variable and there is less creation of this object and you continue to use the same instance which will give you a more evenly distributed stream of PRNs.

- 708
- 5
- 22
There are these main reasons:
Construction of the object is expensive and will reduce the performance of the static method. This may not be true for
Random
, but would justify to cache that object. Just keep in mind that the object used functions should be thread-safe as the static method might be called from different threads on the same time.You just want one instance of the object to be there. This could be like a singleton (one instance) or you just want to reduce the memory used by your function and avoid to allocate multiple instances.
Random
gets initialized during its construction and it is pseudo-random. This means it would return the same values if initialized with the same seed. So multiple parallel calls to your function could construct aRandom
instance with the same sequence of random numbers.
To note: I checked the source code for reason 3 and this is not true for the Random implementation in JDK 8 as it includes a seedUniquifier
function, which generates a random seed in a thread-safe way. Maybe Scary Wombat was not aware of that.

- 526
- 2
- 11
-
It was not Scary Wombat who started to talk about 'reason 3'. Also if this problem is only not a problem in JDK, it is still worth mentioning. – martijnn2008 Nov 19 '15 at 15:13