简体   繁体   English

如果没有清除ThreadLocal变量,会发生什么?

[英]If not cleared ThreadLocal variable, What will happen?

defined a threadlocal variable in a class to maintain some instances. 在类中定义了一个threadlocal变量来维护一些实例。 setting and getting in a recursive method. 设置和获取递归方法。 Somewhat i cant clear the threadlocal variable when the request completes (i have analysed in all other ways. I can't clear threadlocal). 有些我无法在请求完成时清除threadlocal变量(我已经用其他所有方式进行了分析。我无法清除threadlocal)。

My question is, If i didn't clear threadlocal variable for each request, what will happen? 我的问题是,如果我没有为每个请求清除threadlocal变量,会发生什么? What are the impacts? 有什么影响?

The javadoc says: javadoc说:

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). 在一个线程消失之后,它的所有线程局部实例副本都要进行垃圾收集(除非存在对这些副本的其他引用)。

For instance, the implementation here is backed by a HashTable that uses weak references for the key. 例如,这里的实现由HashTable支持,该HashTable使用密钥的弱引用 In this case, the key is the thread. 在这种情况下,键是线程。 If the thread terminates, the entry in the map becomes eligible for garbage collection. 如果线程终止,则映射中的条目将有资格进行垃圾回收。

The garbage colleciton might happen only when the system starts running out of memory space. 垃圾收集可能仅在系统开始耗尽内存空间时才会发生。 But this consideration applies to all objects in the system: when objects start being reclaimed depend on the GC policy, which is VM specifc and subject to tuning. 但是这种考虑适用于系统中的所有对象:当对象开始被回收时,取决于GC策略,这是VM特定的并且可以进行调整。

This is my view of good and bad usage of thread locals: 这是我对线程本地的好坏的看法:

  • It is good ot use thread locals if the point is to address a concurrency issue. 如果要解决并发问题,那么使用线程本地是很好的 For instance, avoiding synchronization of an object that is not thread-safe by keeping one copy per thread . 例如, 通过为每个线程保留一个副本来避免同步非线程安全的对象 Or to address other design issue related to concurrency. 或者解决与并发相关的其他设计问题。

  • It is bad if the point is to "pass a parameter" down the call chain in a cheap way. 如果重点是以便宜的方式“通过参数”向下调用链接,这是很糟糕的 You should better refactor your code and pass the object down the call chain as a regular method paramter. 您应该更好地重构代码并将对象作为常规方法参数传递给调用链。

  • It is ok to use thread local to store some form of "current" context, eg the current request. 是确定使用线程本地存储某种形式的“当前”的背景下,如当前请求的。

If the thread dies, so does the reference to the ThreadLocal entry and so your object (assuming there are no other references) will be garbage collected. 如果线程死亡,那么对ThreadLocal条目的引用也是如此,因此您的对象(假设没有其他引用)将被垃圾收集。

As long as the thread lives, so does your object. 只要线程存在,您的对象也会存在。

You have to assess what the impact is for your object being long-lived. 您必须评估对象长期存在的影响。

You have a memory leak and the ThreadLocal might already be set, the next time your code gets called. 您有内存泄漏,并且下次调用代码时可能已经设置了ThreadLocal。 ThreadLocals are a bit of a code smell imo. ThreadLocals有点代码味道imo。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM