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 ?
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.Randomare threadsafe. However, the concurrent use of the samejava.util.Randominstance across threads may encounter contention and consequent poor performance. Consider instead usingThreadLocalRandomin 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).
I totally agree with Maartens's answer. However one can notice that java.util classes create statics for SecureRandom themselfes.
public final class UUID implements java.io.Serializable, Comparable<UUID> {
...
/*
* The random number generator used by this class to create random
* based UUIDs. In a holder class to defer initialization until needed.
*/
private static class Holder {
static final SecureRandom numberGenerator = new SecureRandom();
}
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