简体   繁体   中英

ThreadLocal Vector cleanup in Java

I'm aware of this similar question, but mine concerns a specific case of ThreadLocal cleanup.

To maintain state on a thread basis I'm storing an (unknown) number of ThreadLocals in a static Vector. Sometimes a "greedy" thread will need more ThreadLocals that are available and as a result the Vector size will be increased. 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).

To clarify: my understanding is that of any given ThreadLocal a different instance will exist for every thread. 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?

Thanks for your help

Please See here the official docs: Vector.trimToSize()

Alternativly: 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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