[concurrency-interest] reusing threads and thread local state

Gregg Wonderly gregg at cytetech.com
Wed May 4 22:36:30 EDT 2005

Osvaldo Pinali Doederlein wrote:
> Humm... I always assumed that ThreadLocal is more efficient and it
> should play better with thread deaths.  I see in the source that it's
> indeed highly customized an optimized, using its own implementation of
> Map, private variables from Thread etc.  Not to mention quoting Donald
> Knuth's algorithms, so I feel better using it ;)

The explicit interaction with Thread creates certain bindings which are 
part of what started this discussion.  Different applications will 
require different behaviors.  Supporting all needs in a single class is 
a hard bargain.  I think Josh is concervative about how extensible 
things should be.  I am torn between the view that ThreadLocal is way 
too focused on a particular application type to be in the jdk, and 
ThreadLocal is just one way to accomodate thread private data.

A different design would have been to use a wrapper around ThreadLocal 
that provided the controlling key.  The wrapper could use an Object key 
to identify the context.  Where ThreadLocal uses a Thread as the map 
key, you'd instead see keys.get(Thread) used.  Each time that you wanted 
to use ThreadLocals, you might do something like:

	Runnable r = ...;
	ThreadLocalContext c = new ThreadLocalContext ( r );

ThreadLocalContext would use a package private interface to ThreadLocal 
to do


bindThread would do

	Object tkey = keys.remove( Thread.currentThread() );
	ValueMap map = new ValueMap();
	maps.put( key, map );
	c.setMap( map );
	keys.put( Thread.currentThread(), key );

Now you have access to ThreadContext in the creating context, and you'd 
have a path from ThreadContext to the ThreadLocal map for that 
ThreadContext.  There would be a direct object graph without a static 
reference or other exposure that would sacrifice the isolation portion 
of the implementation.  Just a thought...

Gregg Wonderly

More information about the Concurrency-interest mailing list