郁闷,本想学习Hibernate来着,看着看着就发现Hibernate用到了ThreadLocal,我嚓,好熟悉,哦,我知道了,本地线程嘛,easy!错,它和线程根本就扯不上任何猫关系(PS:上个月鹿樵问我来着,我说没用过)
对于应用场合和概念就不分析了,javaeye上有人分析的不错了已经。主要看下源码哈。
/**
* Returns the value in the current thread's copy of this thread-local
* variable. Creates and initializes the copy if this is the first time
* the thread has called this method.
*
*/
public Object get() {
Thread t = Thread.currentThread();
//ThreadLocalMap是 static inner class ,骂吧的一提到内部类就想到Hashmap纠结啊! 这个Hashmap维护了key是线程号,value是变量副本的结构
ThreadLocalMap map = getMap(t);
if (map != null)
return map.get(this);//根据thread查找对应的变量副本
// Maps are constructed lazily. if the map for this thread
// doesn't exist, create it, with this ThreadLocal and its
// initial value as its only entry.
//第一次访问的时候才执行,第一次默认返回null,如果不想要null,你懂的,哦,我懂的
Object value = initialValue();
createMap(t, value);
return value;
}
//protected,不用我多说,一看就知道是什么目的,擦,return null
protected Object initialValue() {
return null;
}
//new 一个ThreadLocalMap对象吧,第一次搞进去个null,以后就随便搞吧
void createMap(Thread t, Object firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
public void set(Object value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
其实,感觉就是外面加了一个衣服一样,有get和set方法,内部结构用Hashmap实现,速度快一点点啦。19点30了,赶紧下班走人。哎,hibernate还没看完,到引出这么一坛子事情。