In Java, when should static non final variables be used?
For example
private static int MY_VAR = 0;
Obviously we are not talking about constants here.
public static final int MY_CONSTANT = 1;
In my experience I have often justified them when using a singleton, but then I end up needing to have more than one instance and cause myself great headache and re-factoring.
It seems it is rare that they should be used in practice. What do you think?
Statistics-gathering might use non-final variables, e.g. to count the number of instances created. On the other hand, for that sort of situation you probably want to use AtomicLong
etc anyway, at which point it can be final. Alternatively if you're collecting more than one stat, you could end up with a Statistics
class and a final reference to an instance of it.
It's certainly pretty rare to have (justifiably) non-final static variables.