A Random is created to produce a single value and then dropped
What it finds
new Random().nextInt(10) creates a generator for one number. Generators created in quick succession may start from related seeds, so the numbers are less random than they look, and each creation costs time. One Random kept in a field, or ThreadLocalRandom.current(), serves every call.
From the rule's source, single_use_random.rs.
import java.util.Random; class Picker { private final Random shared = new Random(); int pick(int n) { int a = new Random().nextInt(n);tx0 reports: a new Random is created for one call of nextInt return a + shared.nextInt(n); }} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/java:single-use-random" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/java:single-use-random] reason="..."tx0 explain tx0/java:single-use-random shows the same in the terminal. Found a false positive? Report it.