4-18-ThreadLocal作用

文章目录
  1. 1. ThreadLocal(线程本地变量)
    1. 1.1. 原理(每个线程都有自己的threadlocalmap)
    2. 1.2. 使用场景(数据库连接,session管理)

ThreadLocal(线程本地变量)

提供线程内的局部变量,这种变量在线程的生命周期内起作用,减少同一个线程内多个函数或者组件之间一些公共变量的传递的复杂度。

原理(每个线程都有自己的threadlocalmap)

  1. 每个线程都有自己的threadlocalmap对象,各管各的

  2. 它在thead类中定义:共用的 ThreadLocal 静态实例,将不同对象的引用保存到不同线程的ThreadLocalMap 中

    1
    ThreadLocal.ThreadLocalMap<ThreadLocal, T> threadLocals=null;
  3. 以自己线程为key

  4. 当前线程.threadLocal.get(this);

image-20210716141857254

使用场景(数据库连接,session管理)

1
2
3
4
5
6
7
8
9
10
11
12
13
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;
}