badgerduke
badgerduke

Reputation: 1013

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?

Upvotes: 6

Views: 1429

Answers (3)

Francisco Spaeth
Francisco Spaeth

Reputation: 23903

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.

Upvotes: 10

meriton
meriton

Reputation: 70564

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.

Upvotes: 2

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

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.

Upvotes: 2

Related Questions