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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3