Random used only once¶
ID: java/random-used-onceKind: problemSecurity severity: Severity: warningPrecision: mediumTags: - quality - reliability - correctness - external/cwe/cwe-335Query suites: - java-security-and-quality.qls
Click to see the query in the CodeQL repository
A program that usesjava.util.Random to generate a sequence of pseudo-random numbersshould not create a new instance ofRandom every time a new pseudo-random number is required (for example,newRandom().nextInt()).
According to the Java API Specification:
If two instances of
Randomare created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.
The sequence of pseudo-random numbers returned by these calls depends only on the value of the seed. If you construct a newRandom object each time a pseudo-random number is needed, this does not generate a good distribution of pseudo-random numbers, even though the parameterlessRandom() constructor tries to initialize itself with a unique seed.
Recommendation¶
Create aRandom object once and use the same instance when generating sequences of pseudo-random numbers (by callingnextInt,nextLong, and so on).
Example¶
In the following example, generating a series of pseudo-random numbers, such asnotReallyRandom andnotReallyRandom2, by creating a new instance ofRandom each time is unlikely to result in a good distribution of pseudo-random numbers. In contrast, generating a series of pseudo-random numbers, such asrandom1 andrandom2, by callingnextInt each timeis likely to result in a good distribution. This is because the numbers are based on only oneRandom object.
publicstaticvoidmain(Stringargs[]){// BAD: A new 'Random' object is created every time// a pseudo-random integer is required.intnotReallyRandom=newRandom().nextInt();intnotReallyRandom2=newRandom().nextInt();// GOOD: The same 'Random' object is used to generate// two pseudo-random integers.Randomr=newRandom();intrandom1=r.nextInt();intrandom2=r.nextInt();}