[concurrency-interest] reusing threads and thread local state

David Holmes dholmes at dltech.com.au
Fri Apr 29 21:40:45 EDT 2005


Just adding my 2c.

I agree with Josh, clearing threadlocals only gives you a partial
clean-slate. I'd prefer that people see that a used thread is a used thread,
not pretend that it can be restored to a pristine state.

Really the libraries that make use of Threadlocals in a way that leads to
these problems, should provide a way to clean the slate for a given thread.
But you really need to know exactly how thread locals are being used.

Alternatively thread creation should be so cheap that you don't care. If the
native threads underlying the Java threads were pooled and re-used at the VM
level that might make fresh creation more attractive - pure speculation on
my part.

There is a problem here and it is probably a misuse of thread-locals to
represent an "identity" that is only loosely tied to thread-identity. The
fix really needs to be applied by the libraries and the applications, with
the VM providing a "safety net" to deal with errant libraries. But it isn't
clear what the VM needs to, or can do.

>    - 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?

There is no requirement for the implementation to track thread locals. A few
implementations ago each ThreadLocal tracked per-thread values. While such a
scheme is much less efficient than having each thread maintain
per-ThreadLocal values, it is none-the-less a legitimate implementation
scheme. Trying to find all the ThreadLocals used by a given thread, with
such a scheme, would require some kind of registry be maintained.

I'd certainly like to hear about specific cases where this problem arises.
Perhaps you could point the original requestor to this interest list :)

David Holmes

More information about the Concurrency-interest mailing list