Question:
In Java, consider a hypothetical utility class that's only used during program setup:
class MyUtils { private static MyObject myObject = new MyObject(); /*package*/static boolean doStuff(Params... params) { // do stuff with myObject and params... } }
Will myObject be eligible for garbage collection when it's no longer needed, or will it persist for the entire program's lifetime?
Answer:
Static fields are not eligible for garbage collection while their class is loaded. They can only be collected when the class loader responsible for loading that class is itself garbage collected.
According to the Java Language Specification (JLS) Section 12.7, "Unloading of Classes and Interfaces":
"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, in the provided example, myObject will persist as long as the class MyUtils is loaded. It will not be garbage collected until the class loader that loaded MyUtils is also eligible for garbage collection.
The above is the detailed content of Will Java\'s Garbage Collector Reclaim Static Fields Like `myObject` in `MyUtils`?. For more information, please follow other related articles on the PHP Chinese website!