开发者

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 w开发者_如何学JAVAant 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.


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜