I am using a custom class loader which extends URLClassLoader. I load some classes into my custom class loader and perform some task. Once the task is completed i want to dispose of the class loader. I tried doing that by setting the reference to null.
But this does not garbage collect the class loader.
Is there a way that can help what i want to achieve?
Basically, as @invariant already pointed out, dereferencing all classes loaded by the specific classloader should make that classloader garbage collectable. However, there is (at least) one exception: if a class is serialized, that class (and thus its classloader) is kept referenced internally by ObjectStreamClass
, which is a primordial class and therefore is never garbage collected. So in this case, the classloader can not be garbage collected either until the whole JVM terminates.
See the full explanation here, in the section "Problems related to garbage collection and serialization".
From the ClassLoader doc: Every Class object contains a reference to the ClassLoader that defined it
. This is preventing your loader being collected. You would have to null out all references to the classes and instances of those classes too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With