一、基础概念
ThreadLocal为变量在每个线程中都创建了一个副本,那么每个线程可以访问自己内部的副本变量,使线程之间相互独立互不影响
1.1 同步机制的比较
对于多线程资源共享的问题,同步机制采用了“以时间换空间”的方式,而ThreadLocal采用了“以空间换时间”的方式。
前者仅提供一份变量,让不同的线程排队访问,而后者为每一个线程都提供了一份变量,因此可以同时访问而互不影响。
Threadlocal的最大作用就是 代替同步锁,提高相关性能。
与volatile关键字的对比
在并发编程中,多个线程访问同一个变量,可能读到另一个线程修改后的值,也可能不是修改后的值。
所以volatile保证我读到的是最新的值,而ThreadLocal保证我读到的是不会被其他线程影响到的值。
1.2 使用场景(多用于全局变量)
1.日志统计:计算接口调用耗时时,缓存当前的开始时间,和请求id
2.读写分离时,缓存读写标志。
3.数据库连接管理
-
private
static ThreadLocal<Connection> connectionHolder=
new
ThreadLocal<Connection>() {
-
public Connection
initialValue
() {
-
return DriverManager.getConnection(DB_URL);
-
}
-
};
-
-
public
static Connection
getConnection
() {
-
return connectionHolder.get();
-
}
4.Session管理
-
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;
-
}
5.调用链(参数传递)
如在公司设置的适配器功能
设置cxGoodsPurchasesFromDubboList
-
@Slf4j
-
@Component
-
public
class
CxGoodsPurchasesDtoAdapter
implements
CxGoodsPurchasesDtoTarget {
-
-
private
final ThreadLocal<List<CxGoodsPurchasesFromDubbo>> adaptResultContext =
new
ThreadLocal<>();
-
-
@Resource
-
private CxCommonBO cxCommonBO;
-
-
@Resource
-
private CxMartRService cxMartRService;
-
-
private List<CxGoodsPurchasesFromDubbo> cxGoodsPurchasesFromDubboList;
-
-
@Override
-
public
void
adaptFromDubbo
(List<CxGoodsPurchasesInfo> req) {
-
try {
-
log.info(
"=============start invoke method CxGoodsPurchasesDtoAdapter adaptFromDubbo,param={}", JsonUtils.toJsonTrim(req));
-
if (CollectionUtils.isEmpty(req)) {
-
return;
-
}
-
cxGoodsPurchasesFromDubboList =
new
ArrayList<>();
-
for (CxGoodsPurchasesInfo cxGoodsPurchasesInfo : req) {
-
CxGoodsPurchasesFromDubbo
cxGoodsPurchasesFromDubbo
=
new
CxGoodsPurchasesFromDubbo();
-
cxGoodsPurchasesFromDubbo.setGoodsCode(cxGoodsPurchasesInfo.getGoodsCode());
-
cxGoodsPurchasesFromDubbo.setGoodsName(cxGoodsPurchasesInfo.getGoodsName());
-
cxGoodsPurchasesFromDubbo.setSkuId(cxGoodsPurchasesInfo.getSkuId());
-
cxGoodsPurchasesFromDubbo.setBarCode(cxGoodsPurchasesInfo.getBarCode());
-
cxGoodsPurchasesFromDubbo.setBaseUnit(cxGoodsPurchasesInfo.getBaseUnit());
-
cxGoodsPurchasesFromDubbo.setTaxCode(cxGoodsPurchasesInfo.getTaxCode());
-
cxGoodsPurchasesFromDubbo.setTaxRatio(cxGoodsPurchasesInfo.getTaxRatio());
-
cxGoodsPurchasesFromDubbo.setWeight(cxGoodsPurchasesInfo.getWeight());
-
-
cxGoodsPurchasesFromDubbo.setWareTypeCode(cxGoodsPurchasesInfo.getWareTypeCode());
-
cxGoodsPurchasesFromDubbo.setSource(cxGoodsPurchasesInfo.getSource());
-
cxGoodsPurchasesFromDubbo.setSupplierCode(cxGoodsPurchasesInfo.getSupplierCode());
-
List<CatFrameworkLevel> catFrameworkLevels = cxGoodsPurchasesInfo.getCatFrameworkLevels();
-
setCategoryCode(cxGoodsPurchasesFromDubbo, catFrameworkLevels);
-
setCxGoodsMdl(cxGoodsPurchasesFromDubbo, cxGoodsPurchasesInfo);
-
cxGoodsPurchasesFromDubboList.add(cxGoodsPurchasesFromDubbo);
-
}
-
adaptResultContext.set(cxGoodsPurchasesFromDubboList);
-
log.info(
"adaptResultContext set success,currentThread={}", Thread.currentThread());
-
}
catch (Exception e) {
-
log.error(
"invoke method CxGoodsPurchasesDtoAdapter adaptFromDubbo occur error", e);
-
}
-
}
取cxGoodsPurchasesFromDubboList
-
@CxRouter
-
@Slf4j
-
public
class
CxGoodsHandler
implements
Handler {
-
-
@Resource
-
protected CxGoodsRService cxGoodsRService;
-
@Resource
-
private CxPurchasesConfigService cxPurchasesConfigService;
-
@Resource
-
private CxCommonBO cxCommonBO;
-
-
@Resource
-
private CxGoodsPurchasesDtoAdapter cxGoodsPurchasesDtoAdapter;
-
-
@Resource
-
private CxGoodsFallbackLogsService cxGoodsFallbackLogsService;
-
-
@Override
-
public
void
handle
(List<CxGoodsPurchasesDTO> datas) {
-
-
List<CxGoodsPurchasesFromDubbo> cxGoodsPurchasesFromDubboList = cxGoodsPurchasesDtoAdapter.getAdaptResult();
-
if (CxCollectionUtils.isEmpty(cxGoodsPurchasesFromDubboList)) {
-
log.info(
"cxGoodsPurchasesDtoAdapter getAdaptResult is Empty,start invoke method doInvokeGoodsInterface");
-
doInvokeGoodsInterface(datas);
-
return;
-
}
-
doSetGoodsFromDubbo(datas, cxGoodsPurchasesFromDubboList);
-
log.info(
"=============after invoke method CxGoodsHandler handle,result={}", JsonUtils.toJsonTrim(datas));
-
-
}
二、底层原理分析
2.1 java.lang.Thread#threadLocals属性
每一个Thread 对象均含有一个ThreadLocalMap 类型的成员变量threadLocals ,它存储本线程中所有ThreadLocal对象及其对应的值。
Thread类有一个核心属性threadLocals,这个threadLocals就是用来存储当前线程变量和对应副本值的映射关系的。即让threadLocals引用指向key为threadLocal,value为当前线程的值。
其中键值为当前ThreadLocal变量(该变量与当前线程有关但不是当前线程值),value为变量副本(即T类型的变量的值)。源码如下:
-
/* ThreadLocal values pertaining to this thread. This map is maintained
-
* by the ThreadLocal class. */
-
ThreadLocal.
ThreadLocalMap
threadLocals
=
null;
注意:是Thread类有一个threadLocals变量,而不是ThreadLocal类有threadLocals变量(之前理解搞反了)
2.2 java.lang.ThreadLocal.ThreadLocalMap
-
/**
-
* ThreadLocalMap is a customized hash map suitable only for
-
* maintaining thread local values. No operations are exported
-
* outside of the ThreadLocal class. The class is package private to
-
* allow declaration of fields in class Thread. To help deal with
-
* very large and long-lived usages, the hash table entries use
-
* WeakReferences for keys. However, since reference queues are not
-
* used, stale entries are guaranteed to be removed only when
-
* the table starts running out of space.
-
*/
-
static
class
ThreadLocalMap {
-
-
/**
-
* The entries in this hash map extend WeakReference, using
-
* its main ref field as the key (which is always a
-
* ThreadLocal object). Note that null keys (i.e. entry.get()
-
* == null) mean that the key is no longer referenced, so the
-
* entry can be expunged from table. Such entries are referred to
-
* as "stale entries" in the code that follows.
-
*/
-
static
class
Entry
extends
WeakReference<ThreadLocal<?>> {
-
/** The value associated with this ThreadLocal. */
-
Object value;
-
-
Entry(ThreadLocal<?> k, Object v) {
-
super(k);
-
value = v;
-
}
-
}
ThreadLocalMap 由一个个Entry 对象构成。
Entry 继承自WeakReference<ThreadLocal<?>> ,一个Entry 由ThreadLocal 对象和Object 构
成。由此可见, Entry 的key是ThreadLocal对象,并且是一个弱引用。当没指向key的强引用后,该key就会被垃圾收集器回收,而value为变量值。
2.3 ThreadLocal是如何为每个线程创建变量的副本的
初始时,在Thread里面,threadLocals为空,当通过ThreadLocal变量调用get()方法或者set()方法,就会对Thread类中的threadLocals进行初始化,并且以当前ThreadLocal变量为键值,以ThreadLocal要保存的副本变量为value,存到threadLocals。
然后在当前线程里面,如果要使用副本变量,就可以通过get方法在threadLocals里面查找。
注意:
1.在进行get之前,必须先set,否则会报空指针异常;如果想在get之前不需要调用set就能正常访问的话,必须重写initialValue()方法。
2.3.1 set方法
当执行set方法时,ThreadLocal首先会获取当前线程对象,然后获取当前线程的ThreadLocalMap类型对象。再以当前ThreadLocal对象为key,将值存储进ThreadLocalMap类型对象中。
set方法主要就是初始化threadLocals,不同的线程会new出不同的ThreadLocalMap
-
/**
-
* Sets the current thread's copy of this thread-local variable
-
* to the specified value. Most subclasses will have no need to
-
* override this method, relying solely on the {@link #initialValue}
-
* method to set the values of thread-locals.
-
*
-
* @param value the value to be stored in the current thread's copy of
-
* this thread-local.
-
*/
-
public
void
set
(T value) {
-
Thread
t
= Thread.currentThread();
-
ThreadLocalMap
map
= getMap(t);
-
if (map !=
null)
-
map.set(
this, value);
-
else
-
createMap(t, value);
-
}
可以看到,set(T value)方法为每个Thread对象都创建了一个ThreadLocalMap,并且将value放入ThreadLocalMap中,ThreadLocalMap作为Thread对象的成员变量保存。
2.3.2 get()方法源码分析:
get方法执行过程类似。ThreadLocal首先会获取当前线程对象,然后获取当前线程的ThreadLocalMap对象。再以当前ThreadLocal对象为key,获取对应的value。
-
/**
-
* Returns the value in the current thread's copy of this
-
* thread-local variable. If the variable has no value for the
-
* current thread, it is first initialized to the value returned
-
* by an invocation of the {@link #initialValue} method.
-
*
-
* @return the current thread's value of this thread-local
-
*/
-
public T
get
() {
-
Thread
t
= Thread.currentThread();
-
ThreadLocalMap
map
= getMap(t);
-
if (map !=
null) {
-
ThreadLocalMap.
Entry
e
= map.getEntry(
this);
-
if (e !=
null) {
-
@SuppressWarnings("unchecked")
-
T
result
= (T)e.value;
-
return result;
-
}
-
}
-
return setInitialValue();
-
}
-
-
/**
-
* 获取当前ThreadLocalMap
-
* Get the map associated with a ThreadLocal. Overridden in
-
* InheritableThreadLocal.
-
*
-
* @param t the current thread
-
* @return the map
-
*/
-
ThreadLocalMap
getMap
(Thread t) {
-
return t.threadLocals;
-
}
-
-
-
/**
-
* 初始化threadLocals
-
* Create the map associated with a ThreadLocal. Overridden in
-
* InheritableThreadLocal.
-
*
-
* @param t the current thread
-
* @param firstValue value for the initial entry of the map
-
*/
-
void
createMap
(Thread t, T firstValue) {
-
t.threadLocals =
new
ThreadLocalMap(
this, firstValue);
-
}
-
-
-
-
/**
-
* Variant of set() to establish initialValue. Used instead
-
* of set() in case user has overridden the set() method.
-
*
-
* @return the initial value
-
*/
-
private T
setInitialValue
() {
-
T
value
= initialValue();
-
Thread
t
= Thread.currentThread();
-
ThreadLocalMap
map
= getMap(t);
-
if (map !=
null)
-
map.set(
this, value);
-
else
-
createMap(t, value);
-
return value;
-
}
-
-
-
-
-
-
-
/**
-
* 初始值为空,若想不为空,则需客户端重写
-
* Returns the current thread's "initial value" for this
-
* thread-local variable. This method will be invoked the first
-
* time a thread accesses the variable with the {@link #get}
-
* method, unless the thread previously invoked the {@link #set}
-
* method, in which case the {@code initialValue} method will not
-
* be invoked for the thread. Normally, this method is invoked at
-
* most once per thread, but it may be invoked again in case of
-
* subsequent invocations of {@link #remove} followed by {@link #get}.
-
*
-
* <p>This implementation simply returns {@code null}; if the
-
* programmer desires thread-local variables to have an initial
-
* value other than {@code null}, {@code ThreadLocal} must be
-
* subclassed, and this method overridden. Typically, an
-
* anonymous inner class will be used.
-
*
-
* @return the initial value for this thread-local
-
*/
-
protected T
initialValue
() {
-
return
null;
-
}
我们发现如果没有先set的话,即在map中查找不到对应的存储,则会通过调用setInitialValue方法返回i,而在setInitialValue方法中,有一个语句是T value = initialValue(),
而默认情况下,initialValue方法返回的是null。
重写逻辑可以参考如下:
-
ThreadLocal
<Long
> longLocal
= new ThreadLocal
<Long
>(){
-
protected Long initialValue() {
-
return Thread.currentThread().getId();
-
};
-
};
-
ThreadLocal
<
String
> stringLocal
= new ThreadLocal
<
String
>(){;
-
protected
String initialValue() {
-
return Thread.currentThread().getName();
-
};
-
};
2.3.3 ThreadLocal的remove方法
-
/**
-
* Removes the current thread's value for this thread-local
-
* variable. If this thread-local variable is subsequently
-
* {@linkplain #get read} by the current thread, its value will be
-
* reinitialized by invoking its {@link #initialValue} method,
-
* unless its value is {@linkplain #set set} by the current thread
-
* in the interim. This may result in multiple invocations of the
-
* {@code initialValue} method in the current thread.
-
*
-
* @since 1.5
-
*/
-
public
void
remove
() {
-
ThreadLocalMap
m
= getMap(Thread.currentThread());
-
if (m !=
null)
-
m.remove(
this);
-
}
-
-
-
-
/**
-
* Remove the entry for key.
-
*/
-
private
void
remove
(ThreadLocal<?> key) {
-
Entry[] tab = table;
-
int
len
= tab.length;
-
int
i
= key.threadLocalHashCode & (len-
1);
-
for (
Entry
e
= tab[i];
-
e !=
null;
-
e = tab[i = nextIndex(i, len)]) {
-
if (e.get() == key) {
-
e.clear();
-
expungeStaleEntry(i);
-
return;
-
}
-
}
-
}
ThreadLocal的remove()方法会先将Entry中对key的弱引用断开,设置为null,然后再清除对应的key为null的value。
2.4 ThreadLocal与内存泄漏
2.4.1内存泄漏的原因
ThreadLocalMap使用ThreadLocal的弱引用作为key,如果一个ThreadLocal不存在外部强引用时,Key(ThreadLocal)势必会被GC回收,这样就会导致ThreadLocalMap中key为null, 而value还存在着强引用,只有thead线程退出以后,value的强引用链条才会断掉,但如果当前线程再迟迟不结束的话(如用线程池进行管理的dubbo线程等),这些key为null的Entry的value就会一直存在一条强引用链(红色链条)
下图可以更直接的表示。其中虚线表示弱引用
下图虚线表示弱引用。ThreadLocal对象被GC回收了,那么key变成了null。Map又是通过key拿到的value的对象。
所以,GC在回收了key所占内存后,没法访问到value的值,因为需要通过key才能访问到value对象。另外,如图所示的引用链:CurrentThread -- Map -- Entry -- value ,所以,在当前线程没有被回收的情况下,value所占内存也不会被回收。所以可能会造成了内存溢出。
参考:
1.ThreadLocal内存泄露 ThreadLocal内存泄露_小大宇的博客-CSDN博客_threadlocal 泄露
ThreadLocal原理及内存泄露预防_puppylpg的博客-CSDN博客_threadlocal内存泄漏
ThreadLocal内存溢出问题_幽夜落雨的博客-CSDN博客
2.4.2 如何防止内存泄漏
因为上述的原因,在ThreadLocal这个类的get()、set()、remove()方法,均有实现回收 key 为 null 的 Entry 的 value所占的内存。
所以,为了防止内存泄露(没法访问到的内存),在不会再用ThreadLocal的线程任务末尾,调用一次 上述三个方法的其中一个即可,一般使用remove。
思考
1.threadLocal是如何保证线程之间的值,互相独立的?
由于每一条线程均含有各自私有的ThreadLocalMap容器,这些容器相互独立互不影响,因此不会存在线程安全性问题,从而也无需使用同步机制来保证多条线程访问容器的互斥性。
ThreadLocal对象每次调用set方法,都是设置的是当前线程的threadLocals变量的值。
调用get方法时也是获取当前线程的threadLocals变量。
即ThreadLocalMap对象不一样,且在set/get方法时都按照当前线程设置和获取的。比如线程1的threadLocals变量和线程2threadLocals变量肯定是不同的。
2.ThreadLocal是否会造成内存溢出?
我认为很难造成内存溢出,因为ThreadLocalMap中的Entry继承了WeakReferenc。但可能造成内存泄露。
3.如果key 使用强引用会怎样?
当threadLocalMap的key为强引用回收ThreadLocal时,因为ThreadLocalMap还持有ThreadLocal的强引用,如果没有手动删除或线程没有退出(被线程池管理),ThreadLocal不会被回收,那么将一直占用内存,同样可能导致内存泄漏。并且当前线程很有可能取到之前同名线程的值,造成数据紊乱。
所以使用强引用并不会回收掉ThreadLocal的内存,反而会影响线程之间的相互隔离
@see 14.Java并发编程:深入剖析ThreadLocalhttp://www.cnblogs.com/dolphin0520/p/3920407.html
@see ThreadLocal源码解读http://www.cnblogs.com/micrari/p/6790229.html
4.duboo中使用Threadlocal
首先ThreadLocal是跟着线程走的,而不管是dubbo或者其他的rpc框架或者Springmvc都有个特点:使用的是线程池模型,当线程执行任务结束之后会回到线程池,这时如果在回到线程池之前ThreadLocal没有被清理,当下一次请求拿到这个线程的时候还能读取到之前没有被清理的ThreadLocal的数据,这样显然不是我们想要的结果了。
在 Dubbo 中使用 ThreadLocal ,如果采用默认的设置,每次 Dubbo 调用结束,Dubbo 处理响应线程并不会被销毁, 而是归还到线程池中。而从 ThreadLocal 源码可以看出,每次我们设置的值其实会存在位于 Thread 中 ThreadLocalMap 变量中。
这就导致,下次如果 Dubbo 处理响应恰好继续使用到这个线程,该线程就能调用到上次响应中设置在 ThreadLocal 设置的值。这会导致业务上异常。其实并不止在 Dubbo 中,该案例还会发生在 web项目中,只要相关使用线程池的,都有可能发生。