简体   繁体   中英

Confused about ThreadLocal

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 methods set and get .

Its really easy to understand it.

Imagine that each Thread has a map that associates a value to a ThreadLocal instance. Every time you perform a get or a set on a ThreadLocal , the implemention of ThreadLocal gets the map associated to the current Thread ( Thread.currentThread() ) and perform the get or set in that map using itself as key.

Example:

ThreadLocal tl = new ThreadLocal();
tl.set(new Object()); // in this moment the implementation will do something similar to Thread.getCurrentThread().threadLocals.put(tl, [object you gave]) 

Object obj = t1.get(); // in this moment the implementation will do something similar to Thread.getCurrentThread().threadLocals.get(tl)

And the interesting thing on this is that the ThreadLocal is hierarchic, meaning if you defined a value for a parent Thread it will be accessible from a child one.

You always access the same instance of ThreadLocal for a specific problem but this instance returns a different value for each thread calling the get method.

That's the point : it's easy to find the object but each thread will have its specific own value. Thus you can for example make sure your specific value won't be accessed by two different threads.

You could see it (conceptually) as a kind of HashMap<Thread><V> which would always be accessed with Thread.currentThread() as key.

Because the thread-specific values are not stored in the ThreadLocal object, but the current Thread 's ThreadLocalMap . The ThreadLocal object merely serves as key in these maps.

For details, read the JavaDoc of ThreadLocal and subclasses, or, if you are curious about the implementation, the source code available in every recent JDKs src.zip.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM