RSPEC-2119 should detect global Random object without final

Hi, I find that rule RSPEC-2119 cannot detect global variables. Please review the minimized sample below.

This is a false negative because rand is re-allocated by a new Random object at line 3. This violates the rule definition. Hence, I think we should restrict Random variable by final modifier, otherwise new Random object can lead to low performance and RNG prediction problem.

static Random rand = new Random();  // should report a warning here
public void foo() {
    rand = new Random();  // Here, rand has been re-allocated
    int rValue = rand.nextInt();
  • Used versions
    • sonarqube-
    • sonar-scanner-cli-

Hey @Belle,

Thanks for the feedback and reproducer. I’m not sure about enforcing the final modifier for fields, but at least we should cover the case of reassigned fields prior to invocations (at least for the simple cases).

Note that the problem is not that easy to identify, and you might actually want to have a way to reinitialize a random generator from a method… but probably not the one also using some of its value. we will see what we can do!

Ticket created to track the issue: SONARJAVA-4112


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.