博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring---------ThreadLocal(线程变量副本)
阅读量:6995 次
发布时间:2019-06-27

本文共 7449 字,大约阅读时间需要 24 分钟。

在学Bean的时候,我们都知道Bean有单例的还有多例的。那么我就有一个问题,单例的线程安全问题是怎样解决的呢?

在查找资料的时候,我发现Spring是通过ThreadLocal(线程变量副本来实现的)

参考:

Synchronized实现内存共享,ThreadLocal为每个线程维护一个本地变量。

1. 采用空间换时间,它用于线程间的数据隔离,为每一个使用该变量的线程提供一个副本,每个线程都可以独立地改变自己的副本,而不会和其他线程的副本冲突。
2. ThreadLocal类中维护一个Map,用于存储每一个线程的变量副本,Map中元素的键为线程对象,而值为对应线程的变量副本。
3. 主要用于将私有线程和该线程存放的副本对象做一个映射,各个线程之间的变量互不干扰,在高并发场景下,可以实现无状态的调用,特别适用于各个线程依赖不通的变量值完成操作的场景。

 

从数据结构入手,先看看ThreadLocal的内部结构图:

从上面的结构图,我们已经窥见ThreadLocal的核心机制:

  • 每个Thread线程内部都有一个Map。
  • Map里面存储线程本地对象(key)和线程的变量副本(value)
  • 但是,Thread内部的Map是由ThreadLocal维护的,由ThreadLocal负责向map获取和设置线程的变量值。

所以对于不同的线程,每次获取副本值时,别的线程并不能获取到当前线程的副本值,形成了副本的隔离,互不干扰。

Thread线程内部的Map在类中描述如下:
1 public class Thread implements Runnable {2     /* ThreadLocal values pertaining to this thread. This map is maintained3      * by the ThreadLocal class. */4     ThreadLocal.ThreadLocalMap threadLocals = null;5 }

ThreadLocal的方法比较简单,

  • get()方法用于获取当前线程的副本变量值。
  • set()方法用于保存当前线程的副本变量值。
  • initialValue()为当前线程初始副本变量值。
  • remove()方法移除当前前程的副本变量值。

1.get()方法

1 /** 2  * Returns the value in the current thread's copy of this 3  * thread-local variable.  If the variable has no value for the 4  * current thread, it is first initialized to the value returned 5  * by an invocation of the {
@link #initialValue} method. 6 * 7 * @return the current thread's value of this thread-local 8 */ 9 public T get() {10 Thread t = Thread.currentThread();11 ThreadLocalMap map = getMap(t);12 if (map != null) {13 ThreadLocalMap.Entry e = map.getEntry(this);14 if (e != null)15 return (T)e.value;16 }17 return setInitialValue();18 }19 20 ThreadLocalMap getMap(Thread t) {21 return t.threadLocals;22 }23 24 private T setInitialValue() {25 T value = initialValue();26 Thread t = Thread.currentThread();27 ThreadLocalMap map = getMap(t);28 if (map != null)29 map.set(this, value);30 else31 createMap(t, value);32 return value;33 }34 35 protected T initialValue() {36 return null;37 }
步骤:
1.获取当前线程的ThreadLocalMap对象threadLocals
2.从map中获取线程存储的K-V Entry节点。
3.从Entry节点获取存储的Value副本值返回。
4.map为空的话返回初始值null,即线程变量副本为null,在使用时需要注意判断NullPointerException。

ThreadLocal进行get的时候,是从当前线程Thread中获取到有且唯一的ThreadLocalMap对象(Thread的ThreadLocalMap属性如果为空,也就是说这个线程从来都没有用过ThreadLocal设置过值,返回null),然后把自己做为键去该Map里面找,找到就返回对于的value,没有就返回null。

2.set()方法
1 /** 2  * Sets the current thread's copy of this thread-local variable 3  * to the specified value.  Most subclasses will have no need to 4  * override this method, relying solely on the {
@link #initialValue} 5 * method to set the values of thread-locals. 6 * 7 * @param value the value to be stored in the current thread's copy of 8 * this thread-local. 9 */10 public void set(T value) {11 Thread t = Thread.currentThread();12 ThreadLocalMap map = getMap(t);13 if (map != null)14 map.set(this, value);15 else16 createMap(t, value);17 }18 19 ThreadLocalMap getMap(Thread t) {20 return t.threadLocals;21 }22 23 void createMap(Thread t, T firstValue) {24 t.threadLocals = new ThreadLocalMap(this, firstValue);25 }

步骤:

1.获取当前线程的成员变量map
2.map非空,则重新将ThreadLocal和新的value副本放入到map中。
3.map空,则对线程的成员变量ThreadLocalMap进行初始化创建,并将ThreadLocal和value副本放入map中。

​​​​ThreadLocal进行set的时候,是在当前线程Thread中获取到有且唯一的ThreadLocalMap对象(如果没有就新建一个ThreadLocalMap对象设置进Thread的属性里),

然后把自己作为键,value作为值set进这个Map里。

 

3.remove()方法

1 /** 2  * Removes the current thread's value for this thread-local 3  * variable.  If this thread-local variable is subsequently 4  * {
@linkplain #get read} by the current thread, its value will be 5 * reinitialized by invoking its {
@link #initialValue} method, 6 * unless its value is {
@linkplain #set set} by the current thread 7 * in the interim. This may result in multiple invocations of the 8 * initialValue method in the current thread. 9 *10 * @since 1.511 */12 public void remove() {13 ThreadLocalMap m = getMap(Thread.currentThread());14 if (m != null)15 m.remove(this);16 }17 18 ThreadLocalMap getMap(Thread t) {19 return t.threadLocals;20 }

 

ThreadLocal中最重要的部分就是内部的ThreadLocalMap,ThreadLocalMap没有实现Map接口,用独立的方式实现了Map功能,其内部的Entry也独立实现。

在ThreadLocalMap中,也是用Entry来保存K-V结构数据的。但是Entry中key只能是ThreadLocal对象,这点被Entry的构造方法已经限定死了。

1 static class Entry extends WeakReference
{2 /** The value associated with this ThreadLocal. */3 Object value;4 5 Entry(ThreadLocal k, Object v) {6 super(k);7 value = v;8 }9 }

Entry继承自WeakReference(弱引用,生命周期只能存活到下次GC前),但只有Key是弱引用类型的,Value并非弱引用。

 

ThreadLocalMap的成员变量:

1 static class ThreadLocalMap { 2     /** 3      * The initial capacity -- MUST be a power of two. 4      */ 5     private static final int INITIAL_CAPACITY = 16; 6  7     /** 8      * The table, resized as necessary. 9      * table.length MUST always be a power of two.10      */11     private Entry[] table;12 13     /**14      * The number of entries in the table.15      */16     private int size = 0;17 18     /**19      * The next size value at which to resize.20      */21     private int threshold; // Default to 022 }

Hash冲突怎么解决

和HashMap的最大的不同在于,ThreadLocalMap结构非常简单,没有next引用,也就是说ThreadLocalMap中解决Hash冲突的方式并非链表的方式,

而是采用线性探测的方式,所谓线性探测,就是根据初始key的hashcode值确定元素在table数组中的位置,如果发现这个位置上已经有其他key值的元素被占用,

则利用固定的算法寻找一定步长的下个位置,依次判断,直至找到能够存放的位置。

ThreadLocalMap解决Hash冲突的方式就是简单的步长加1或减1,寻找下一个相邻的位置。
1 /** 2  * Increment i modulo len. 3  */ 4 private static int nextIndex(int i, int len) { 5     return ((i + 1 < len) ? i + 1 : 0); 6 } 7  8 /** 9  * Decrement i modulo len.10  */11 private static int prevIndex(int i, int len) {12     return ((i - 1 >= 0) ? i - 1 : len - 1);13 }

显然ThreadLocalMap采用线性探测的方式解决Hash冲突的效率很低,如果有大量不同的ThreadLocal对象放入map中时发送冲突,或者发生二次冲突,则效率很低。

 

所以这里引出的良好建议是:每个线程只存一个变量,这样的话所有的线程存放到map中的Key都是相同的ThreadLocal,如果一个线程要保存多个变量,

就需要创建多个ThreadLocal,多个ThreadLocal放入Map中时会极大的增加Hash冲突的可能。

 

ThreadLocalMap的问题

由于ThreadLocalMap的key是弱引用,而Value是强引用。这就导致了一个问题,ThreadLocal在没有外部对象强引用时,发生GC时弱引用Key会被回收,

而Value不会回收,如果创建ThreadLocal的线程一直持续运行,那么这个Entry对象中的value就有可能一直得不到回收,发生内存泄露。

如何避免泄漏

既然Key是弱引用,那么我们要做的事,就是在调用ThreadLocal的get()、set()方法时完成后再调用remove方法,将Entry节点和Map的引用关系移除,

这样整个Entry对象在GC Roots分析后就变成不可达了,下次GC的时候就可以被回收。

如果使用ThreadLocal的set方法之后,没有显示的调用remove方法,就有可能发生内存泄露,所以养成良好的编程习惯十分重要,使用完ThreadLocal之后,记得调用remove方法。

应用场景

还记得Hibernate的session获取场景吗

1 private static final ThreadLocal
threadLocal = new ThreadLocal
(); 2 3 //获取Session 4 public static Session getCurrentSession(){ 5 Session session = threadLocal.get(); 6 //判断Session是否为空,如果为空,将创建一个session,并设置到本地线程变量中 7 try { 8 if(session ==null&&!session.isOpen()){ 9 if(sessionFactory==null){10 rbuildSessionFactory();// 创建Hibernate的SessionFactory11 }else{12 session = sessionFactory.openSession();13 }14 }15 threadLocal.set(session);16 } catch (Exception e) {17 // TODO: handle exception18 }19 20 return session;21 }

每个线程访问数据库都应当是一个独立的Session会话,如果多个线程共享同一个Session会话,有可能其他线程关闭连接了,当前线程再执行提交时就会出现会话已关闭的异常,

导致系统异常。此方式能避免线程争抢Session,提高并发下的安全性。

使用ThreadLocal的典型场景正如上面的数据库连接管理,线程会话管理等场景,只适用于独立变量副本的情况,如果变量为全局共享的,则不适用在高并发下使用。

总结

  • 每个ThreadLocal只能保存一个变量副本,如果想要上线一个线程能够保存多个副本以上,就需要创建多个ThreadLocal。
  • ThreadLocal内部的ThreadLocalMap键为弱引用,会有内存泄漏的风险。
  • 适用于无状态,副本变量独立后不影响业务逻辑的高并发场景。如果如果业务逻辑强依赖于副本变量,则不适合用ThreadLocal解决,需要另寻解决方案。

转载于:https://www.cnblogs.com/levontor/p/11048474.html

你可能感兴趣的文章
JAVA 23种开发模式详解(代码举例)
查看>>
Windows上搭建Flume运行环境
查看>>
Linux系统排查4——网络篇
查看>>
文件操作
查看>>
Implement strStr()
查看>>
hough T
查看>>
cannot download, /home/azhukov/go is a GOROOT, not a GOPATH
查看>>
设计模式之简单工厂模式
查看>>
使用ArcEngine开发自定义Tool并发布为GP服务
查看>>
Intel超低功耗CPU的一些信息
查看>>
Qt之信号与槽
查看>>
PDM/PLM系统授权模型的研究和应用(转载)
查看>>
Winform下的Datagrid的列风格(4)—DataGridComboBoxTableViewColumn
查看>>
上传图片 以及做成缩略图
查看>>
封装和多态
查看>>
POJ - 3041 Asteroids 【二分图匹配】
查看>>
luogu P4198 楼房重建——线段树
查看>>
使用property为类中的数据添加行为
查看>>
程序设计基础知识
查看>>
复变函数与积分变换
查看>>