I just learned about ThreadLocal this morning. I read that it should always be final and static like:
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
(Session is a Hibernate Session)
My confusion is this: Because it is static, it is available to any thread in the JVM. Yet it will hold information local to each thread which accesses it? I’m trying to wrap my head around this so I apologize if this is unclear. Each thread in the application has access to the same ThreadLocal object, but the ThreadLocal object will store objects local to each thread?
Yes, the instance would be the same, but the code attaches the value you set with the
Thread.currentThread(), when you set and when you retrieve, so the value set will be accessible just within the current thread when accessed using the methodssetandget.Its really easy to understand it.
Imagine that each
Threadhas a map that associates a value to aThreadLocalinstance. Every time you perform a get or a set on aThreadLocal, the implemention ofThreadLocalgets the map associated to the currentThread(Thread.currentThread()) and perform thegetorsetin that map using itself as key.Example:
And the interesting thing on this is that the
ThreadLocalis hierarchic, meaning if you defined a value for a parentThreadit will be accessible from a child one.