tags:

views:

1663

answers:

5

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?

+6  A: 

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.

Jon Skeet
+1, but do use the Atomics. Considering it's "static," assume multiple threads will access.
Jason Cohen
+2  A: 

When used as a cache, logging, statistics or a debug switch are the obvious reasonable uses. All private, of course.

If you have mutable object assigned to a final field, that is morally the same as having a mutable field.

Some languages, such as Fan, completely disallow mutable statics (or equivalent).

Tom Hawtin - tackline
A: 

In my experience static non-final variables should only be used for singleton instances. Everything else can be either more cleanly contained by a singleton (such as a cache), or made final (such as a logger reference). However I don't believe in hard and fast rules, so I would take my advice with a grain of salt. That said I would suggest carefully examining any case where you consider declaring a non-final static variable aside from a singleton instance and see if it can be refactored or implemented differently -- i.e. moved into a singleton container or use a final reference to a mutable object.

Chris B.
A: 

I think wrapping your statics and providing access via singletons (or at a minimum via static methods) is generally a good idea, since you can better control access and avoid some race condition and synchronization issues.

Uri
A: 

A static variable means that it is available to the class as a whole so both examples are available to the class as a whole. Final means that the value cannot be changed. So I guess the question is when do you want to a value to be available to an entire class and it cannot be changed after it has been instantiated. My guess would be a constant available to all instantiations of that class. Otherwise if you need something like a population counter then the non-final variable.

uriDium