Confused about ThreadLocal

I just found out 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 - hibernation session)

My confusion is this: since it is static, it is accessible to any thread in the JVM. But will it store information locally for each thread that accesses it? I try to circle my head, so I apologize if this is unclear. Each thread in the application has access to one ThreadLocal object, but will a ThreadLocal object store objects locally for each thread?

+6
source share
3 answers

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()); // 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 interestingly, ThreadLocal is hierarchical, that is, if you defined a value for the parent Thread , it will be available from the child.

+10
source

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

What a point: it's easy to find an object, but each thread will have its own meaning. Thus, you can, for example, make sure that your specific value will not be available for two different threads.

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

+2
source

Because thread- ThreadLocalMap values ​​are not stored in the ThreadLocal object, but the current thread is ThreadLocalMap . The ThreadLocal object simply serves as the key in these maps.

For details, see. The JavaDoc ThreadLocal and subclasses, or, if you're wondering about the implementation of the source code is available in each of the last JDK src.zip.

+2
source

Source: https://habr.com/ru/post/918966/


All Articles