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?
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?
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:
Class
object representing the class is still reachableClassLoader
that loaded the class is still reachableClassLoader
are still reachableWhen none of those are true, then the
ClassLoader
and 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.class
in a directory (not package!)x
. It's source code is:Then create a class
TestMe
in the parent directory ofx
:Running
TestMe
will produce this (or similar) output:In the second to last line we see that the
GCTester
instance is finalized, which can only mean that the class (andClassLoader
) are eligible for garbage collection.