Garbage Collection of Static Fields
A common question arises regarding the fate of static fields when they are no longer referenced. Consider the following utility class intended for program setup:
class MyUtils { private static MyObject myObject = new MyObject(); /*package*/static boolean doStuff(Params... params) { // do stuff with myObject and params... } }
Will the myObject field be garbage collected once it is no longer in use, or will it persist throughout the program's execution?
To answer this, we must understand the nature of static variables. Static variables are allocated memory at class loading time and exist for the lifetime of the class. The garbage collector cannot reclaim them as long as the class is loaded.
According to the Java Language Specification (JLS) Section 12.7:
A class or interface may be unloaded if and only if its defining class loader may be reclaimed by the garbage collector [...] Classes and interfaces loaded by the bootstrap loader may not be unloaded.
Therefore, static variables in loaded classes cannot be garbage collected until the corresponding class loader is itself collected. As bootstrap classes are not unloadable, static variables in those classes will persist indefinitely.
In the case of MyUtils, since it is not loaded by the bootstrap class loader, its static myObject field can be garbage collected once the program no longer requires MyUtils, regardless of whether it is used or not.
The above is the detailed content of Will Static Fields Be Garbage Collected When No Longer Referenced?. For more information, please follow other related articles on the PHP Chinese website!