如何清理 ThreadLocals [英] How to clean up ThreadLocals

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

问题描述

有没有人有一个例子如何做到这一点?它们是否由垃圾收集器处理?我使用的是 Tomcat 6.

Does any one have an example how to do this? Are they handled by the garbage collector? I'm using Tomcat 6.

推荐答案

javadoc 是这样说的:

The javadoc says this:

"只要线程处于活动状态并且 ThreadLocal 实例可访问,每个线程都持有对其线程局部变量副本的隐式引用;在线程消失后,其线程局部实例的所有副本均受制于到垃圾收集(除非存在对这些副本的其他引用).

"Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

如果您的应用程序或(如果您正在谈论请求线程)容器使用线程池,则意味着线程不会死亡.如有必要,您需要自己处理线程本地人.唯一干净的方法是调用 ThreadLocal.remove() 方法.

If your application or (if you are talking about request threads) container uses a thread pool that means that threads don't die. If necessary, you would need to deal with the thread locals yourself. The only clean way to do this is to call the ThreadLocal.remove() method.

您可能希望为线程池中的线程清理线程局部变量的原因有两个:

There are two reasons you might want to clean up thread locals for threads in a thread pool:

  • 防止内存(或假设的资源)泄漏,或
  • 防止信息通过线程局部变量从一个请求意外泄漏到另一个请求.

线程本地内存泄漏通常不应该是有界线程池的主要问题,因为任何线程本地都可能最终被覆盖;即当线程被重用时.但是,如果您犯了一遍又一遍地创建新的 ThreadLocal 实例的错误(而不是使用 static 变量来保存单例实例),则线程本地值将获胜不会被覆盖,并且会累积在每个线程的 threadlocals 映射中.这可能会导致严重泄漏.

Thread local memory leaks should not normally be a major issue with bounded thread pools since any thread locals are likely to get overwritten eventually; i.e. when the thread is reused. However, if you make the mistake of creating a new ThreadLocal instances over and over again (instead of using a static variable to hold a singleton instance), the thread local values won't get overwritten, and will accumulate in each thread's threadlocals map. This could result in a serious leak.

假设您正在谈论在 web 应用程序处理 HTTP 请求期间创建/使用的线程本地变量,那么避免线程本地泄漏的一种方法是使用您的 web 应用程序的 ServletRequestListener 注册一个 ServletRequestListenercode>ServletContext 并实现侦听器的 requestDestroyed 方法来清理当前线程的线程局部变量.

Assuming that you are talking about thread locals that are created / used during a webapp's processing of an HTTP request, then one way to avoid the thread local leaks is to register a ServletRequestListener with your webapp's ServletContext and implement the listener's requestDestroyed method to cleanup the thread locals for the current thread.

请注意,在这种情况下,您还需要考虑信息从一个请求泄漏到另一个请求的可能性.

Note that in this context you also need to consider the possibility of information leaking from one request to another.

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

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