Yes, the instance will be the same, but the code adds the value set using Thread.currentThread()
when you install and when you retrieve, so the set of values ββwill only be available in the current thread when accessed using the set
and get
methods.
Its really easy to understand.
Suppose each Thread
has a mapping that maps a value to an instance of ThreadLocal
. Each time you execute get or set on ThreadLocal
, the ThreadLocal
implementation receives the map associated with the current Thread
( Thread.currentThread()
) and executes get
or set
on this map, using as a key.
Example:
ThreadLocal tl = new ThreadLocal(); tl.set(new Object());
And interestingly, ThreadLocal
is hierarchical, that is, if you defined a value for the parent Thread
, it will be available from the child.
source share