views:

111

answers:

4

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?

+2  A: 

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.

invariant
+1  A: 

there's a 6-year-old bug at http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4950148 that seems to be what you want. unfortunately no such functionality seems to have been implemented yet...

oedo
+2  A: 

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

Péter Török
A: 

As long as any of the classes loaded by this classloader is referenced, the classloader will not be garbage-collected. So the classloader will be removed if: all direct references to the classloader are nulled, all references to classes loaded by this classloader and to instances of these classes. Then it can be dumped on the next run of the garbage-collector.

Mnementh