[concurrency-interest] Re: Soliciting input about removeAllThreadLocals

David Walend david@walend.net
Mon, 09 Dec 2002 11:06:58 -0500


>> I'd be thrilled if it wasn't necessary.  This is not a case of blind 
>>optimization, but rather a hard-won piece of knowledge -- creating a 
>>new Thread for every operation (servlet invocation, e.g.) is 
>>prohibitively expensive. 
>   I'm with you.  Thread pooling is a *necessary* evil.
>>But if I'm not mistaken, you guys are about to bless the concept of 
>>thread pools by adding it to the core libraries?  Are we seeing signs 
>>of dissension among the ranks of the experts here? 
>Nope.  As Doug says, we all agree.  The one point on which there's 
>dissension is the need for Thread.removeAllThreadLocals();  I'm in the 
>"over my dead body" camp : )
Does this sum up the arguments for and against 
Thread.removeAllThreadLocals(); ?


Against: ThreadLocals can have the same scope as other member variables. 
So removing ThreadLocals that are out of scope is a violation of the 
protected/package/private scope contract, and will lead to unwelcome 
side effects.

For: removeAllThreadLocals() makes cleaning up threads when they return 
to thread pools possible and simple. Cleaning up will prevent unwelcome 
side effects.


Is that it? Or is it deeper? (Or did I walk in on Act 5 of a five act play?)

If that's it, how about adding a safty check to prevent others from 
calling removeAllThreadLocals() within the method?

Something like:

        throw IllegalStateException("Don't call this method while the 
Thread is still alive, Dave.");

That way, the method could only be called on dead Threads, presumably 
after they've been returned to the pool. Thread pooling becomes a 
necessary evil, with simple clean-up supported by a state check.

If the pool you're using does call removeAllThreadLocals(), you'd be 
responsible for putting back the ones you need. If your pool doesn't 
call removeAllThreadLocals(), you'd have to do your own clean up (which 
is just where we'll be without that method).

Does that fix the problem, or just move it somewhere else? Are there any 
uses for accessing ThreadLocals from a dead (or dead-and-revived) Thread?

Hope that adds something. Thanks,


David Walend