[concurrency-interest] Soliciting input about removeAllThreadLocals
Mon, 9 Dec 2002 09:28:42 +0000
Joshua Bloch wrote,
> I actually wrote a piece taxonomizing the uses of ThreadLocal many
> years ago when I campaigned to put them in the libraries. I'll try
> to dig it up. I think it would be more than a little bit
> entertaining to look at resets in the context of each usage.
You mailed me a version of this a couple of years ago when we were
having a (very) minor disagreement about ThreadLocals,
Here's a list that I made when I first proposed adding the ThreadLocal
1) Associating "genuine thread context" with a thread - The context
is typically temporary (e.g., the user or transaction on whose
behalf a thread is currently executing, the prevailing rounding
mode or precision for some class of numerical computation, the
operative permissions). Less frequently, there may be uses for
permanent thread context.
2) Performance - Some objects are, by their nature "thread singleton
objects": while they do not represent true thread context, a
given thread will never use more than one of them. If they are
expensive to construct, it makes sense to permanently associate
a thread the first time the thread needs such an object. This
differs from case 1 in that the object doesn't maintain any
interesting state between uses. An example might be an open
connection to a database.
3) Sleazery - Thread-local variables can be used to effectively
add extra parameters (in or out) to a method without changing
its signature. This is not terribly good practice, and should
rarely, if ever, be necessary.
4) Making legacy APIs thread-safe - Back in the bad old days,
statics were used to hold state from call-to-call (e.g.,
strtok()) or to return supplemental information (e.g., errno).
Such APIs can be made thread-safe by replacing statics with
thread-locals. Hopefully we have no such legacy APIs in the Java
The only thing I had to add was this observation, which relates to one
of Lukes objections (ie. that (1) is tantamount to (3)),
(1) _could_ be dealt with by explicity representing thread context in
interfaces and propagating it through the call chain (which is another
form of TSS, natch). That's often extremely ugly, tho' and also
fragile if the context set can change (ie. you'd have to add/change
context params all along the call chain). Using TSS to avoid this is
perfectly legitimate: in effect it's a lightweight form of aspect