I am trying to use a SecureRandom
to generate random numbers in my java project. But I am a little confused as how to keep my object for SecureRandom
. Should it be a static
class member. I dont intend to call this from outside. Below is my current implementation :
Class MyClass { private static final SecureRandom secureRandom = new SecureRandom(); private long calculate(int noOfRetry){ final long value = someValueCalculationWith-noOfRetry; final float randomNo = secureRandom().nextFloat() + 1; return (long) (value*randomNo); } }
Is this the correct way to use SecureRandom in java ?
Advertisement
Answer
No, don’t make it static
. If you want you can make it an instance field, but making it a class field is not optimal. E.g. see the note on thread-safety on the Random
class that it has been derived from:
Instances of
java.util.Random
are threadsafe. However, the concurrent use of the samejava.util.Random
instance across threads may encounter contention and consequent poor performance. Consider instead usingThreadLocalRandom
in multithreaded designs.
Beware though that the ThreadLocalRandom
is not cryptographically secure, and therefore not a good option for you. In general, you should try and avoid using static
class fields, especially when the instances are stateful.
If you only require the random instance in one or a few methods that are not in a tight loop then making it a local instance is perfectly fine (just using var rng = new SecureRandom()
in other words, or even just new SecureRandom()
if you have a single method call that requires it).