5

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?

java_geek
  • 17,585
  • 30
  • 91
  • 113
  • See http://stackoverflow.com/questions/148681/unloading-classes-in-java/148707#148707 – Yuval Adam Mar 31 '10 at 10:56
  • Not _quite_ the same question, this one is about unloading the classloader rather than the loaded classes. – Nick Moore Mar 31 '10 at 10:58
  • 1
    My first advice would be to check what makes your classes inside your classloader not garbageable. Make a dump and analyze the dependencies to the classes hold by your classloader. – Matthieu BROUILLARD Mar 31 '10 at 11:29

5 Answers5

3

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
  • 114,404
  • 31
  • 268
  • 329
2

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.

Nick Moore
  • 15,547
  • 6
  • 61
  • 83
1

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

chris
  • 9,745
  • 1
  • 27
  • 27
1

The ClassLoader will be garbage collected after there are no more instances of classes created by the ClassLoader. There is an old bug (4950148) related to there being no way to explicitly dispose of a ClassLoader, which causes problems for example with file locking.

This has now been fixed in JDK 7 which adds an URLClassLoader.close() method.

Esko Luontola
  • 73,184
  • 17
  • 117
  • 128
0

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
  • 50,487
  • 48
  • 148
  • 202