Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java SecureRandom declaration should be static class specific or can be instance specific

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 ?

like image 602
Som Avatar asked Apr 17 '26 15:04

Som


2 Answers

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 same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom 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).

like image 197
Maarten Bodewes Avatar answered Apr 20 '26 07:04

Maarten Bodewes


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();
    }
like image 45
user17477134 Avatar answered Apr 20 '26 08:04

user17477134