前言:
我们都知道ThreadLocal能做到线程数据隔离,那么底层到底是怎么做到的,通过解析源码来一探究竟!
首先我们来看看ThreadLocal的最重要的set方法,源代码如下:
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
1、Thread t = Thread.currentThread();
首先获取当前正在执行的线程t,
2、ThreadLocalMap map = getMap(t);
//ThreadLocal类中的方法:
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
//Thread类中方法:
ThreadLocal.ThreadLocalMap threadLocals = null;
原来当前线程Thread中有一个ThreadLocalMap对象,我们来看看这个ThreadLocalMap对象:
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. */
Ob