简体   繁体   English

Java中的ThreadLocal矢量清理

[英]ThreadLocal Vector cleanup in Java

I'm aware of this similar question, but mine concerns a specific case of ThreadLocal cleanup. 我所知道的这个类似的问题,但我关注的ThreadLocal清理的具体情况。

To maintain state on a thread basis I'm storing an (unknown) number of ThreadLocals in a static Vector. 为了维护基于线程的状态,我将(未知)数量的ThreadLocals存储在静态Vector中。 Sometimes a "greedy" thread will need more ThreadLocals that are available and as a result the Vector size will be increased. 有时,“贪婪的”线程将需要更多可用的ThreadLocals,因此,Vector的大小将增加。 While the cleanup using ThreadLocal.remove() is not a problem in my scenario, I wonder if it will ever be possible to shrink the Vector size after a greedy thread dies or if it is bound to only grow (or at best remain the same). 虽然在我的场景中使用ThreadLocal.remove()进行清理不是问题,但我想知道是否有可能在贪婪的线程死后缩小Vector的大小,或者它是否只能增长(或保持不变) )。

To clarify: my understanding is that of any given ThreadLocal a different instance will exist for every thread. 需要说明的是:我的理解是,对于任何给定的ThreadLocal,每个线程都将存在一个不同的实例。 How could then my static Vector know, when it is accessed from thread A, that the values of ThreadLocal T are empty for all existing threads? 那么,从线程A访问我的静态Vector时,如何知道所有现有线程的ThreadLocal T的值为空?

Thanks for your help 谢谢你的帮助

Please See here the official docs: Vector.trimToSize() 请在这里查看官方文档: Vector.trimToSize()

Alternativly: Vector.setSize() 或者: Vector.setSize()

The task you are trying to achieve is illogical. 您试图实现的任务是不合逻辑的。 From current thread you can not know if ThreadLocal is used by another thread and how many threads are using it at all. 从当前线程中,您不知道ThreadLocal是否被另一个线程使用,以及有多少线程正在使用它。 You can try to combine ThreadLocals with WeakHashMap(or Guava's cache), but that will be a very strange solution, try to prevent growing of ThreadLocals. 您可以尝试将ThreadLocals与WeakHashMap(或Guava的缓存)结合使用,但这将是一个非常奇怪的解决方案,请尝试防止ThreadLocals的增长。

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

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