Random Instance Used Only Once

ID

java.random_used_once

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

reliability

Description

Reports single-use new Random() instances such as new Random().nextInt(). Creating a fresh Random for each call can produce correlated or predictable output because consecutive instances may be seeded from close clock values.

Rationale

java.util.Random is a linear congruential generator whose output quality depends on the seed. When two instances are created in quick succession they may share the same or adjacent seed values, producing identical or highly correlated sequences.

// Bad - new Random for every call
int a = new Random().nextInt(100);
int b = new Random().nextInt(100); // may equal a

Remediation

Reuse a single Random instance or use ThreadLocalRandom.

// Good - reuse a single instance
private final Random rng = new Random();
int a = rng.nextInt(100);

// Or better - ThreadLocalRandom
int b = ThreadLocalRandom.current().nextInt(100);

References