Until few weeks back, I thought I understand when to make fields and methods static
or non-static
. For example, when a field (say object of another class) is unique for any number of objects for the class, it should be made static
.
But then I read about JVM garbage collection a few weeks back.
I understand that static
fields are never garbage collected and remain in memory all along, unless the class loader itself is garbage collected.
But if I don't make that field static
, at least it will be garbage collected.
So, it seems there is a very thin line between making fields/methods static or not.
Can anybody please explain to me this thin line in deciding, so that my application is way more efficient.
Fields are not made
static
over garbage collection. That is whole new area to consider. If the memory is huge for yourstatic
field, yeah you should make itnon-static
.It might be thin but there is very clear distinction. You declare a field as static when it is not at all related to any instance of a class.
A simple usecase of static field is declaring constants using
final
keyword, e.g.:Same is the case with methods also. You declare a method as static when it is not dependent on instance of a class OR the state of the class. That's the reason a static method cannot use instance members of a class.
These are not mandatory rules, but it is better to follow them:
When to use static fields:
final
too.SessionFactory
in HibernateUtils).Remember that, static fields shall usually be immutable during runtime of your application (they are sometimes modified during start-up and tear-down of the application).
When to use static methods:
static
to gain a little performance.Static fields is a concept you should really think carefully about before using it as a method to increase the efficiency of your application.
As you know when static modifier is included in a field , no instance of the class is required for it to be used. And as a result it has a the same value for the entire application. On one hand it can lead to many bugs in multi-threaded read/write environment if you don't properly serialize the access, on the other hand it is good thing if you trying to create singleton pattern (A field with a value that do not change during the life time of the application and therefor do not need to be GC)
By and large you should avoid read/write static fields, it will introduce more bugs into your application. Having the same value across many instances of the same class is not considered a good use case for static field in OO design. Not because it is less or more efficient but because it breaks the concept of encapsulation.