Unloading of static fields in java
I came across this interesting article about loading and unloading of static fields which details a couple of facts I was not aware of
1. Loading – You can get a reference to a class, before it has been initialized (i.e its static fields being initialized or its static initializers being called), only when it is used does it get initialized. The link contains an example code which illustrates this fact.
2. Unloading – Static fields are unloaded when the Class’ classloader is unloaded. This is unloaded when a GC is performed and there are no strong references from the threads’ stacks.
This post adds more detail to the second point. Below are few reasons why classes are unloaded only when the classloader unloads.
1. A class is only unloaded when it is garbage collected, and for that to happen there must be no references to it anywhere. And the classloader keeps a reference to each class it loads. It keeps a reference to it so if it is asked to load it again it can just return the same one. Otherwise you would have multiple instances of the same class object being loaded with different refs to them floating around.
2. Since we can never guarantee that unloading a class or interface whose loader is potentially reachable will not cause reloading, the reloading may not be transparent if the class has static variables (whose state would be lost) and static initializers (which may have side effects).