1. Thread 内存有 ThreadLocal 的 ThreadLocalMap 成员
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
2. ThreadLocal 定义了针对该 ThreadLocalMap 的操作函数,如 get set
/**
* Returns the value in the current thread's copy of this
* thread-local variable. If the variable has no value for the
* current thread, it is first initialized to the value returned
* by an invocation of the {@link #initialValue} method.
*
* @return the current thread's value of this thread-local
*/
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}/**
* Sets the current thread's copy of this thread-local variable
* to the specified value. Most subclasses will have no need to
* override this method, relying solely on the {@link #initialValue}
* method to set the values of thread-locals.
*
* @param value the value to be stored in the current thread's copy of
* this thread-local.
*/
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}/**
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @return the map
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
梳理一下:get 调用 ==> 根据当前线程取得线程的 ThreadLocalMap ==> 以当前 ThreadLocal 实例为 key 取出 value
set 调用 ==> 根据当前线程取得线程的 ThreadLocalMap ==> 以当前 ThreadLocal 实例为 key 设置 value
因此,一个 ThreadLocal 也就能在一个线程里设置一个值
3. 用于 Session 管理的示例
通常是弄一个类似工具类(比如 Context)的东西,线程使用其静态方法进行 get/set/remove
ThreadLocal 实例并不需要定义到 Thread 中
Context.getSession() 就能得到当前线程的 session 了
private static final ThreadLocal threadSession = new ThreadLocal();
public static Session getSession() throws InfrastructureException {
Session s = (Session) threadSession.get();
try {
if (s == null) {
s = getSessionFactory().openSession();
threadSession.set(s);
}
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
return s;
}