我如何“关闭"一个ClassLoader? [英] How do I "close" a ClassLoader?

查看:382
本文介绍了我如何“关闭"一个ClassLoader?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下,我需要在应用程序中创建许多类加载器,以在运行用户提供的脚本时临时使一些代码可见.我为此使用URLClassLoader,效果很好.

I have a case where I need to create a lot of class loaders in my application to temporarily make some code visible while user supplied scripts are running. I'm using an URLClassLoader for this and it works pretty well.

当脚本终止时,我想卸载"或关闭"类加载器以释放资源.

When the script terminates, I want to "unload" or "close" the class loader to free the resources.

将对类加载器的引用设置为null是否足够?我特别想知道我是否最终会用完文件句柄,因为额外的类在JAR文件中.

Is it enough to set the reference to the class loader to null? I'm especially wondering if I'll eventually run out of file handles because the extra classes are in JAR files.

PS:必须与Java 5及更高版本一起使用.是的,我知道...

PS: Must work with Java 5 and up. Yeah, I know...

推荐答案

当类加载器加载的所有类不再具有任何引用,并且对类加载器本身的所有引用已被擦除时,类加载器及其类加载后将被作为一个组进行垃圾收集.

When all classes that the class loader loaded no longer have any references, and all references to the class loader itself have been erased, the class loader and the classes it loaded will be garbage collected as a group.

请注意,这取决于是否设置了JVM属性,该属性会导致卸载未引用的类.在大多数环境中,它都是默认设置,但在某些嵌入式情况下可能不是.

Note that this is dependent on having the JVM attribute set that causes unreferenced classes to be unloaded. It's set by default in most environments, but may not be in some embedded cases.

[请注意,删除对类的引用不是一件容易的事.当然,任何其他通过名称引用它的类都将阻止删除.因此,必须使用ClassLoader.findClass或类似的东西来加载该类.]

[Note that it's a non-trivial matter to remove references to a class. Any other class that references it by name will of course prevent removal. So the class must be loaded using ClassLoader.findClass or something similar.]

这篇关于我如何“关闭"一个ClassLoader?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆