原文连接:http://www.cnblogs.com/dolphin0520/p/3920407.html
感谢做者的辛苦总结!html
Java并发编程:深刻剖析ThreadLocal数据库
想必不少朋友对ThreadLocal并不陌生,今天咱们就来一块儿探讨下 ThreadLocal的使用方法和实现原理。首先,本文先谈一下对ThreadLocal的理解,而后根据ThreadLocal类的源码分析了其实现 原理和使用须要注意的地方,最后给出了两个应用场景。编程
如下是本文目录大纲:安全
一.对ThreadLocal的理解服务器
二.深刻解析ThreadLocal类多线程
三.ThreadLocal的应用场景并发
ThreadLocal,不少地方叫作线程本地变量,也有些地方叫作线程本地存储,其实意思差很少。可能不少朋友都知道ThreadLocal为变量在每一个线程中都建立了一个副本,那么每一个线程能够访问本身内部的副本变量。源码分析
这句话从字面上看起来很容易理解,可是真正理解并非那么容易。性能
咱们仍是先来看一个例子:this
1 class ConnectionManager { 2 3 private static Connection connect = null; 4 5 public static Connection openConnection() { 6 if(connect == null){ 7 connect = DriverManager.getConnection(); 8 } 9 return connect; 10 } 11 12 public static void closeConnection() { 13 if(connect!=null) 14 connect.close(); 15 } 16 }
假设有这样一个数据库连接管理类,这段代码在单线程中使用是没有任何问题的,可是若是在多线程中使用呢?很显然,在多线程中使用会存在线程安 全问题:第一,这里面的2个方法都没有进行同步,极可能在openConnection方法中会屡次建立connect;第二,因为connect是共享 变量,那么必然在调用connect的地方须要使用到同步来保障线程安全,由于极可能一个线程在使用connect进行数据库操做,而另一个线程调用 closeConnection关闭连接。
因此出于线程安全的考虑,必须将这段代码的两个方法进行同步处理,而且在调用connect的地方须要进行同步处理。
这样将会大大影响程序执行效率,由于一个线程在使用connect进行数据库操做的时候,其余线程只有等待。
那么你们来仔细分析一下这个问题,这地方到底需不须要将connect变量进行共享?事实上,是不须要的。假如每一个线程中都有一个 connect变量,各个线程之间对connect变量的访问其实是没有依赖关系的,即一个线程不须要关心其余线程是否对这个connect进行了修改 的。
到这里,可能会有朋友想到,既然不须要在线程之间共享这个变量,能够直接这样处理,在每一个须要使用数据库链接的方法中具体使用时才建立数据库连接,而后在方法调用完毕再释放这个链接。好比下面这样:
1 class ConnectionManager { 2 3 private Connection connect = null; 4 5 public Connection openConnection() { 6 if(connect == null){ 7 connect = DriverManager.getConnection(); 8 } 9 return connect; 10 } 11 12 public void closeConnection() { 13 if(connect!=null) 14 connect.close(); 15 } 16 } 17 18 19 class Dao{ 20 public void insert() { 21 ConnectionManager connectionManager = new ConnectionManager(); 22 Connection connection = connectionManager.openConnection(); 23 24 //使用connection进行操做 25 26 connectionManager.closeConnection(); 27 } 28 }
这样处理确实也没有任何问题,因为每次都是在方法内部建立的链接,那么线程之间天然不存在线程安全问题。可是这样会有一个致命的影响:致使服 务器压力很是大,而且严重影响程序执行性能。因为在方法中须要频繁地开启和关闭数据库链接,这样不尽严重影响程序执行效率,还可能致使服务器压力巨大。
那么这种状况下使用ThreadLocal是再适合不过的了,由于ThreadLocal在每一个线程中对该变量会建立一个副本,即每一个线程内部 都会有一个该变量,且在线程内部任何地方均可以使用,线程之间互不影响,这样一来就不存在线程安全问题,也不会严重影响程序执行性能。
可是要注意,虽然ThreadLocal可以解决上面说的问题,可是因为在每一个线程中都建立了副本,因此要考虑它对资源的消耗,好比内存的占用会比不使用ThreadLocal要大。
在上面谈到了对ThreadLocal的一些理解,那咱们下面来看一下具体ThreadLocal是如何实现的。
先了解一下ThreadLocal类提供的几个方法:
1 public T get() { } 2 public void set(T value) { } 3 public void remove() { } 4 protected T initialValue() { }
get()方法是用来获取ThreadLocal在当前线程中保存的变量副本,set()用来设置当前线程中变量的副本,remove()用 来移除当前线程中变量的副本,initialValue()是一个protected方法,通常是用来在使用时进行重写的,它是一个延迟加载方法,下面会 详细说明。
首先咱们来看一下ThreadLocal类是如何为每一个线程建立一个变量的副本的。
先看下get方法的实现:
第一句是取得当前线程,而后经过getMap(t)方法获取到一个map,map的类型为ThreadLocalMap。而后接着下面获取到<key,value>键值对,注意这里获取键值对传进去的是 this,而不是当前线程t。
若是获取成功,则返回value值。
若是map为空,则调用setInitialValue方法返回value。
咱们上面的每一句来仔细分析:
首先看一下getMap方法中作了什么:
可能你们没有想到的是,在getMap中,是调用当期线程t,返回当前线程t中的一个成员变量threadLocals。
那么咱们继续取Thread类中取看一下成员变量threadLocals是什么:
实际上就是一个ThreadLocalMap,这个类型是ThreadLocal类的一个内部类,咱们继续取看ThreadLocalMap的实现:
能够看到ThreadLocalMap的Entry继承了WeakReference,而且使用ThreadLocal做为键值。
而后再继续看setInitialValue方法的具体实现:
很容易了解,就是若是map不为空,就设置键值对,为空,再建立Map,看一下createMap的实现:
至此,可能大部分朋友已经明白了ThreadLocal是如何为每一个线程建立变量的副本的:
首先,在每一个线程Thread内部有一个ThreadLocal.ThreadLocalMap类型的成员变量threadLocals,这个 threadLocals就是用来存储实际的变量副本的,键值为当前ThreadLocal变量,value为变量副本(即T类型的变量)。
初始时,在Thread里面,threadLocals为空,当经过ThreadLocal变量调用get()方法或者set()方法,就会对 Thread类中的threadLocals进行初始化,而且以当前ThreadLocal变量为键值,以ThreadLocal要保存的副本变量为 value,存到threadLocals。
而后在当前线程里面,若是要使用副本变量,就能够经过get方法在threadLocals里面查找。
下面经过一个例子来证实经过ThreadLocal能达到在每一个线程中建立变量副本的效果:
这段代码的输出结果为:
从这段代码的输出结果能够看出,在main线程中和thread1线程中,longLocal保存的副本值和stringLocal保存的副本值都不同。最后一次在main线程再次打印副本值是为了证实在main线程中和thread1线程中的副本值确实是不一样的。
总结一下:
1)实际的经过ThreadLocal建立的副本是存储在每一个线程本身的threadLocals中的;
2)为什么threadLocals的类型ThreadLocalMap的键值为ThreadLocal对象,由于每一个线程中可有多个threadLocal变量,就像上面代码中的longLocal和stringLocal;
3)在进行get以前,必须先set,不然会报空指针异常;
若是想在get以前不须要调用set就能正常访问的话,必须重写initialValue()方法。
由于在上面的代码分析过程当中,咱们发现若是没有先set的话,即在map中查找不到对应的存储,则会经过调用setInitialValue方法返回i, 而在setInitialValue方法中,有一个语句是T value = initialValue(), 而默认状况下,initialValue方法返回的是null。
看下面这个例子:
1 public class Test { 2 ThreadLocal<Long> longLocal = new ThreadLocal<Long>(); 3 ThreadLocal<String> stringLocal = new ThreadLocal<String>(); 4 5 public void set() { 6 longLocal.set(Thread.currentThread().getId()); 7 stringLocal.set(Thread.currentThread().getName()); 8 } 9 10 public long getLong() { 11 return longLocal.get(); 12 } 13 14 public String getString() { 15 return stringLocal.get(); 16 } 17 18 public static void main(String[] args) throws InterruptedException { 19 final Test test = new Test(); 20 21 System.out.println(test.getLong()); 22 System.out.println(test.getString()); 23 24 Thread thread1 = new Thread(){ 25 public void run() { 26 test.set(); 27 System.out.println(test.getLong()); 28 System.out.println(test.getString()); 29 }; 30 }; 31 thread1.start(); 32 thread1.join(); 33 34 System.out.println(test.getLong()); 35 System.out.println(test.getString()); 36 } 37 }
在main线程中,没有先set,直接get的话,运行时会报空指针异常。
可是若是改为下面这段代码,即重写了initialValue方法:
1 public class Test { 2 ThreadLocal<Long> longLocal = new ThreadLocal<Long>(){ 3 protected Long initialValue() { 4 return Thread.currentThread().getId(); 5 }; 6 }; 7 ThreadLocal<String> stringLocal = new ThreadLocal<String>(){; 8 protected String initialValue() { 9 return Thread.currentThread().getName(); 10 }; 11 }; 12 13 14 public void set() { 15 longLocal.set(Thread.currentThread().getId()); 16 stringLocal.set(Thread.currentThread().getName()); 17 } 18 19 public long getLong() { 20 return longLocal.get(); 21 } 22 23 public String getString() { 24 return stringLocal.get(); 25 } 26 27 public static void main(String[] args) throws InterruptedException { 28 final Test test = new Test(); 29 30 test.set(); 31 System.out.println(test.getLong()); 32 System.out.println(test.getString()); 33 34 35 Thread thread1 = new Thread(){ 36 public void run() { 37 test.set(); 38 System.out.println(test.getLong()); 39 System.out.println(test.getString()); 40 }; 41 }; 42 thread1.start(); 43 thread1.join(); 44 45 System.out.println(test.getLong()); 46 System.out.println(test.getString()); 47 } 48 }
就能够直接不用先set而直接调用get了。
最多见的ThreadLocal使用场景为 用来解决 数据库链接、Session管理等。
如:
1 private static ThreadLocal<Connection> connectionHolder 2 = new ThreadLocal<Connection>() { 3 public Connection initialValue() { 4 return DriverManager.getConnection(DB_URL); 5 } 6 }; 7 8 public static Connection getConnection() { 9 return connectionHolder.get(); 10 }
下面这段代码摘自:
http://www.iteye.com/topic/103804
1 private static final ThreadLocal threadSession = new ThreadLocal(); 2 3 public static Session getSession() throws InfrastructureException { 4 Session s = (Session) threadSession.get(); 5 try { 6 if (s == null) { 7 s = getSessionFactory().openSession(); 8 threadSession.set(s); 9 } 10 } catch (HibernateException ex) { 11 throw new InfrastructureException(ex); 12 } 13 return s; 14 }