Re: ThreadLocal question
On 11/5/2014 3:05 AM, mike wrote:
Hi,
When we do the following:
private static ThreadLocal myParameter = new InheritableThreadLocal();
Why dont you do it like this:
private static ThreadLocal myParameter = new ThreadLocal ();
Since myParameter is a ThreadLocal anyway right?
InheritableThreadLocal is a subclass of ThreadLocal, a "special
kind of" ThreadLocal, if you will. Every InheritableThreadLocal is
a ThreadLocal, but not every ThreadLocal is an InheritableThreadLocal.
(A Schnauzer is a "special kind of" Dog and every Schnauzer is a Dog,
but not every Dog is a Schnauzer.)
If you want the "special" behavior of InheritableThreadLocal, a
generic ThreadLocal won't do (you cannot enter just any Dog in a
kennel club Schnauzer show). Your second initialization is entirely
legal, but it won't give you InheritableThreadLocal behavior.
A third thing you might have written would be
private static InheritableThreadLocal myParameter
= new InheritableThreadLocal();
.... and this would work just fine, giving you the special behavior
you wanted. However, you might prefer to localize the knowledge of
the special behavior to just the place where the initialization happens,
and not burden the rest of the program with it. That's what the first
version does: It creates an InheritableThreadLocal to get the special
behavior, and then tells the rest of the program "Here's a ThreadLocal
you can use, and never mind about exactly what flavor it is." One
benefit of this approach is that if someday you invent yet another
special version of ThreadLocal, like SelfDestructingThreadLocal, you
can drop it in just by changing the initialization, and not need to
go changing Inheritable to SelfDestructing throughout the program.
(If you've declared myParameter as a Dog and initialized it with an
instance of a Schnauzer, you can later switch to a Schnoodle much
more easily than if you'd written Schnauzer everywhere.)
--
esosman@comcast-dot-net.invalid
"Don't be afraid of work; make work afraid of you." -- TLM