Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

disposing a class loader

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?

like image 219
java_geek Avatar asked Mar 31 '10 10:03

java_geek


2 Answers

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".

like image 59
Péter Török Avatar answered Sep 28 '22 10:09

Péter Török


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.

like image 33
Nick Moore Avatar answered Sep 28 '22 11:09

Nick Moore