Java – confused about ThreadLocal
I just learned about ThreadLocal this morning I read that it should always be final and static:
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
(session is a hibernate session)
My confusion is that because it is static, it can be used by any thread in the JVM However, does it store local information for each thread accessing it? I'm trying to get around this, so I'll apologize if I don't know Each thread in the application can access the same ThreadLocal object, but the ThreadLocal object will store the local object of each thread?
Solution
Yes, the instance will be the same, but when you set up and retrieve, the code will append the thread you use The value set by currentthread(), so when using method access, you can access the value set in the current thread and get
It's really easy to understand
Imagine that each thread has a mapping that associates a value with a ThreadLocal instance Each time get or set is executed on ThreadLocal, the implementation of ThreadLocal will obtain the mapping associated with the current thread (thread. Currentthread()), and use itself as a key to execute get or set in the mapping
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)
Interestingly, ThreadLocal is hierarchical, which means that if you define a value for the parent thread, it will be accessible from the child thread