问题描述
有人有一个例子如何做到这一点?它们是由垃圾收集器处理的吗?我正在使用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说:
只要线程处于活动状态并且ThreadLocal实例可访问,每个线程都拥有对其线程局部变量副本的隐式引用;在线程消失后,它的所有副本线程局部实例受垃圾收集(除非存在对这些副本的其他引用)。
如果您的应用程序或(如果您是谈论请求线程)容器使用一个线程池,这意味着线程不会死。如果有必要,你需要自己处理线程本地。唯一干净的方法是调用 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:
- 以防止内存(或假设资源)泄漏,或
- 以防止意外ntal通过线程本地从一个请求泄漏到另一个请求。
线程本地内存泄漏通常不应该是有界线程的主要问题池,因为任何线程本地可能最终被覆盖;即当线程被重用时。但是,如果你错误地反复创建一个新的 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.
假设您正在讨论在webapp期间创建/使用的线程局部文件处理HTTP请求,然后避免线程本地泄漏的一种方法是使用您的webapp的 ServletContext
注册 ServletRequestListener
并实现侦听器的 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!