Singleton Java class can have static constant variable ? Sonar lint error

In Java singleton class, I want to make a final constant like below code.

  1. private final int threshold = 3; // Noncompliant Code Example by Sonal lint
  2. private static final int THRESHOLD = 3; // Compliant code by Sonarlint

My question is, why singleton class should have the static keyword in a final int/string constant as this class has only one instance?

3 answers

  • answered 2018-11-08 08:34 Mureinik

    This is probably a caveat that Sonar Lint can't recognize. It's pretty hard to recognize a singleton with static analysis, so they just opted to ignore this caveat and issue a warning anyway.

    While theoretically you're right (there's just one instance, so the constant will be declared only once anyway), you may be better off saving future maintainers of this code the confusion (and the need to configure Sonar to ignore this warning), and just define it as static too. You also may gain a minute memory consumption improvement if the compiler actually inlines it, which AFAIK, it only does with static final members.

  • answered 2018-11-08 08:53 ETO

    This is an ordinary declaration of a constant in java.

    private static final int THRESHOLD = 3;
    

    It means that all the instances of your class will access the same field.

    When you declare it like private final int THRESHOLD = 3; this means that every instance of your class will have its own copy of THRESHOLD field. It does not make any sense to declare it non-static when you immediately initialize it:

    private final int THRESHOLD = 3;
    

    Declaring non-static final fields makes sense when you initialize them in constructor. Thus all the instances have the same constant field with different values:

    private final int threshold;
    
    protected YourConstructor(int threshold){
        this.threshold = threshold;
    }
    

    Just follow Sonarlint's advice and declare it as a static constant.

  • answered 2018-11-08 09:04 RolandMinten

    Sonarlint is not sure you're declaring a singleton. It tries to avoid hypothetical bugs in future.