0

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

Community
  • 1
  • 1
Raul Bertone
  • 146
  • 7

2 Answers2

1

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

Alternativly: Vector.setSize()

Jan
  • 1,042
  • 8
  • 22
  • Hi, thanks. I am aware of that, but my question is not how to do it but rather if it is at all possible to shrink such a Vector. – Raul Bertone Mar 13 '13 at 13:15
  • @RaulBertone I've never used these, but reading the docs it looks like calling `setSize()` followed by `trimToSize()` would do exactly what you want. – Windle Mar 13 '13 at 13:28
  • If you install a nice IDE it is rather easy to CTRL+Click into that code. There you will find an array copy to a smaller array, so the vector is truly reduced in memory footprint. – Jan Mar 13 '13 at 15:16
0

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.

Mikhail
  • 4,175
  • 15
  • 31
  • I suppose I agree with you, that's why I'm wondering what the program behaviour would be in such a situation. Anyhow, I came up with a better implementation that uses ThreadLocal instead of Vector, so there is now only one ThreadLocal per thread. Still, what if? :-) – Raul Bertone Mar 13 '13 at 14:45