I asked a question about Garbage Collection in Java in this topic.
But the answer I got, gave me another question.
Someone mentioned that classes can be collected by the garbage collector too.
Is this true?
And if it is true, how does this work?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A class in Java can be garbage-collected when nothing references it. In most simple setups this never happens, but there are situations where it can occur.
There are many ways to make a class reachable and thus prevent it from being eligible for GC:
Classobject representing the class is still reachableClassLoaderthat loaded the class is still reachableClassLoaderare still reachableWhen none of those are true, then the
ClassLoaderand all classes it loaded are eligible for GC.Here’s a constructed example (full of bad practices!) that should demonstrate the behaviour:
Create a bytecode file
GCTester.classin a directory (not package!)x. It’s source code is:Then create a class
TestMein the parent directory ofx:Running
TestMewill produce this (or similar) output:In the second to last line we see that the
GCTesterinstance is finalized, which can only mean that the class (andClassLoader) are eligible for garbage collection.