setContextClassLoader含义 [英] setContextClassLoader implications

查看:156
本文介绍了setContextClassLoader含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试清理由于创建自己的线程而导致内存泄漏的Tomcat警告。 http://wiki.apache.org/tomcat/MemoryLeakProtection 建议我拨打 myThread.setContextClassLoader(null)在启动线程之前。

I'm trying to clean up Tomcat warnings about memory leaks due to creating my own threads. http://wiki.apache.org/tomcat/MemoryLeakProtection proposes that I call myThread.setContextClassLoader(null) prior to starting the thread.

这次电话的含义是什么? run()方法中的代码是否仍然能够从我的应用程序中解析类?

What is the implication of this call? Will the code in the run() method still be able to resolve classes from my application?

推荐答案

是的。 Thread.getContextClassLoader()是一种通用框架从类加载器树的下游加载资源的机制。

Yes it will. The Thread.getContextClassLoader() is a mechanism for generic frameworks load resources from further down the class loader tree.

以Tomcat的类加载器层次结构为例。

Take Tomcat's class loader hierarchy.

      Bootstrap
          |
       System
          |
       Common
       /     \
  Webapp1   Webapp2 ... 

servlet或JSP框架驻留在 Common 类加载器中。如果其中一个框架要从 Webapp1 加载类路径资源,他们可以尝试:

The servlet or JSP framework resides in the Common class loader. If one of these frameworks is to load a classpath resource from Webapp1, they could try:

getClass().getResource("/some/resource/in/webapp1"); // fail

但由于类加载机制仅委托调用类加载器链,因此会失败。这意味着所有需要加载资源的框架都会:

But since class loading mechanics only delegates calls up the class loader chain, this would fail. This means that all frameworks that needs to load a resource instead do:

Thread.currentThread().getContextClassLoader().getResource("/some/resource/in/webapp1");

并且servlet容器确保这是 Webapp1 线程在该上下文中执行时的类加载器。所以线程的上下文类加载器实际上是框架从错误的方向加载类的一种方式。

And the servlet container makes sure this is the Webapp1 class loader whenever the thread is executing in that context. So the thread's context classloader is effectively a way for frameworks to load classes from "the wrong direction".

当你产生一个新线程时,该线程默认获得其父级的上下文类加载器(您的 Webapp1 类加载器)。如果您因此停止 Webapp1 ,那么tomcat应该能够通过GC进行webapp,但是只要有任何引用留给 Webapp1 类加载器 - 因此警告。

When you spawn a new thread, that thread gets, by default the context class loader of its parent (your Webapp1 classloader). If you consequently stop Webapp1, tomcat is supposed to be able to GC that webapp, but is unable to do so as long as there's any reference left to the Webapp1 class loader - hence the warning.

关于上下文类加载器的好文章

这篇关于setContextClassLoader含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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