[concurrency-interest] reusing threads and thread local state
Pete.Soper at Sun.COM
Fri Apr 29 17:39:43 EDT 2005
An RFE was recently submitted to Sun with this description:
"Threads are often reused rather than destroyed and recreated, e.g. in a
Thread pooled server. In that case, it would be nice, even necessary, to
be able to clear out all ThreadLocalS that were set during the previous
use of the Thread so that the Thread is reset to its first-created
state. This could be a clearThreadLocals() method on a Thread instance
or a static clearAll() method on ThreadLocal class.
When a Thread is reused by a framework the intent is for it to be as if
the Thread were just created. ThreadLocalS should not be left over from
the previous use of the Thread.
Whether or not this type of Thread reuse is a good idea or not, it is in
wide use and Java should provide a way to accommodate this usage.
CUSTOMER SUBMITTED WORKAROUND :
The only partial workaround is to manually keep track of all
ThreadLocals used and set them to null or remove them at the end of the
Thread use. This is obviously not optimal, and in many cases, not
I'd like to poll this list with the following questions to start some
- Is this as attractive as it seems? That is, isn't it just a recipe
for memory leaks? Or perhaps I'm too cautious to think user's might tend
to overlook persistent references to local objects being part of their
responsibilty? Tracking references would seem to make tracking the
locals themselves the easy part in some cases. Or perhaps I'm
misinterpreting the behavior expected. Perhaps others read this as "go
find the references and null them out too"?
- Are Java implementations obligated to accurately track locals
associated with a given thread? I haven't read the specs carefully to
look for this detail but nothing related to this has jumped out at me.
It looks like this could be painful for an implementation taking a
completely different approach to implementing ThreadLocal vs
InheritedThreadLocal.Or maybe that's bogus thinking. Maybe the
requirements implicit with InheritedThreadLocal make the ability to
track the general population of per-thread locals. Thoughts?
- Why not Thread.firstCreatedState()? That is, is a focus on local
state too narrow? I can't think of much state beyond the locals that
would be relevant (but I've only been thinking about threads for two
weeks and most of that has been silly stuff like "I need *what* to build
J2SE on Windows??" Apologies in advance for the ignorance I will
- The suggested static method seems problematic. For example, it
would be frustrating when you'd like it to operate on almost all the
threads, or more likely, the threads you are aware of but no others. Is
there some reason why it shouldn't be rejected out of hand?
More information about the Concurrency-interest