- 例
- 源码分析
- ThreadLocal#Entry
- ThreadLocal#nextHashCode
- ThreadLocal#HASH_INCREMENT
- ThreadLocal#threadLocalHashCode
- Thread#threadLocals
- ThreadLocal#get()
- ThreadLocal#getMap()
- ThreadLocal#ThreadLocalMap#getEntry()
- ThreadLocal#set()
- ThreadLocal#createMap()
- ThreadLocal#ThreadLocalMap#set()
- ThreadLocal#ThreadLocalMap#replaceStaleEntry()
- ThreadLocal#ThreadLocalMap#expungeStaleEntry()
- ThreadLocal#ThreadLocalMap#cleanSomeSlots()
- 程序实例
- 总结
例
Hibernate中典型的ThreadLocal的代码。1
2
3
4
5
6
7
8
9
10
11
12
13
14private 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;
}
可以看到在getSession()方法中,首先判断当前线程中有没有放进去session,如果还没有,那么通过sessionFactory().openSession()来创建一个session,再将session set到线程中,实际是放到当前线程的ThreadLocalMap这个map中。这时,对于这个session的唯一引用就是当前线程中的那个ThreadLocalMap,而threadSession作为这个值的key,要取得这个session可以通过threadSession.get()来得到,里面执行的操作实际是先取得当前线程中的ThreadLocalMap,然后将threadSession作为key将对应的值取出。这个session相当于线程的私有变量,而不是public的。
ThreadLocal是在每个线程中有一个map,而将ThreadLocal实例作为key,这样每个map中的项数很少,而且当线程销毁时相应的东西也一起销毁了。 这样设计也防止内存泄漏,1个线程被销毁,这个线程内的对象都被销毁。