[concurrency-interest] reusing threads and thread local state
jmanson at cs.purdue.edu
Fri Apr 29 18:25:12 EDT 2005
When we were doing the memory model, we came across the need for a
"final field safe context". One of the guarantees it provides is that
if you are in a thread that read an improperly published version of the
object, and you enter a final field safe context, and you only see
properly published versions of the object within that context, you will
get your final field guarantees back.
(For those not in the know: if Thread A is constructing an object and
places a reference to it where another thread can see it (or "publishes"
the reference) before the constructor finishes, and then Thread B reads
that reference, Thread B isn't guaranteed to see the correct values for
the final fields of that object. If Thread A waits until the object is
done constructing before publishing the reference, then Thread B is
guaranteed to see the correct values for the final fields of that object.)
I have often thought that some interface to final field contexts that
also covers ThreadLocals should exist. In effect, create a
"runInLogicalThread" method that takes a Runnable, executes it in a
final field safe context, and provides a "fresh slate" for the
ThreadLocals. When you return, the ThreadLocals are reset to their
original values, and final fields are (potentially) no longer safe.
I posted this idea to this list a year or two back, but it sort of
fizzled. I can't remember why now, though. Now that people are
thinking about final fields (a little), maybe it is time to think about
Or do you think this solution is as problematic as the idea of having a
Joshua Bloch wrote:
> Oh no, not again. I fought this so many times over the years. It's
> one of those ideas that seems good on the surface but isn't. My
> analogy is used cars vs. new cars. If you want a new car / thread,
> you have have to pay a bit more for it. If you go to a used car lot /
> thread pool, the car may have a few dings on it / thread may have a
> bit of state associated with it. If you can live with this, buy a
> used car / use a thread pool. If not, buy a new car / create a
> Also, resetting ThreadLocal state does not produce a virgin thread.
> There is other hidden state associated with a thread. Some of it can
> be external to the thread (e.g., it can be registered in a static data
> structure). With threads as with people, you can only be a virgin
> once. Yow, are we mixing meaphors yet?
> Java has a powerful access control model. It lets you write provably
> correct programs. Letting one thread muck with another's ThreadLocal
> variables eats into this access model. Just say no.
> My 2 cents,
More information about the Concurrency-interest