前言
ThreadLocal是JDK包提供的,它提供了线程本地变量,也就是如果你创建了一个ThreadLocal变量,那么访问这个变量的每个线程都会有这个变量的一个本地副本。当多线程操作这个变量时,实际操作的是自己本地内存里面的变量,从而避免了线程安全问题。
ThreadLocal的应用
列举个使用ThreadLocal的例子
static ThreadLocal<String> localV = new ThreadLocal<>();
public static void main(String[] args) {
Thread threadOne = new Thread(new Runnable() {
@Override
public void run() {
localV.set("thradOne local V");
System.out.println("getV = " + localV.get());
}
});
Thread threadTwo = new Thread(new Runnable() {
@Override
public void run() {
localV.set("thradTwo local V");
System.out.println("getV = " + localV.get());
}
});
threadOne.start();
threadTwo.start();
}
Out:
getV = thradTwo local V
getV = thradOne local V
threadOne通过ThreadLocal的set方法设置的值,其实设置的是线程本地内存中的一个副本,这个副本是threadTwo访问不了的。
ThreadLocal是如何实现线程之间数据隔离
ThreadLocal其实就是一个工具壳,真正实现存储的还是ThreadLocalMap,相应的变量存储在Thread类中
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
/*
* InheritableThreadLocal values pertaining to this thread. This map is
* maintained by the InheritableThreadLocal class.
*/
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
ThreadLocalMap是一个定制化的HashMap,默认情况下这两个变量都为空。
inheritableThreadLocals:init方法初始化,同一个ThreadLocal变量在父进程中被设置值后,使用inheritableThreadLocals可以在子线程中获取
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc,
boolean inheritThreadLocals) {
//获取当前的线程,这里指的是main函数所在的线程,也就是父线程
Thread parent = currentThread();
if (inheritThreadLocals && parent.inheritableThreadLocals != null) //因为main线程set/get方法操作的是inheritableThreadLocals,一定不为空
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
}
static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
return new ThreadLocalMap(parentMap);
}
threadLocals:只有当线程第一次调用ThreadLocal的set/get方法时才会创建
public void set(T value) {
Thread t = Thread.currentThread(); //获取当前线程
ThreadLocalMap map = getMap(t); //查找当前线程threadlocals变量
if (map != null)
map.set(this, value);
else
createMap(t, value);//第一次调用就创建当前线程对应的HashMap
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
最后我们分析一下ThreadLocalMap类是如何实现线程本地化存储
ThreadLocalMap类
static class ThreadLocalMap {
//table中每个结点,ThreadLocal为弱引用 当没有引用的时候会直接回收
static class Entry extends WeakReference<ThreadLocal<?>> {
//ThreadLocal关联的值
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
//数组的初始化大小
private static final int INITIAL_CAPACITY = 16;
//存储ThreadLocal的数组
private Entry[] table;
//默认为数组大小的三分之二
private int threshold; // Default to 0
/**
* Set the resize threshold to maintain at worst a 2/3 load factor.
*/
private void setThreshold(int len) {
threshold = len * 2 / 3;
}
tip:
- ThreadLocalMap初始化大小为16 大于数组三分之二便进行扩容
- ThreadLocal为弱引用
存值调用的ThreadLocalMap.set方法
private void set(ThreadLocal<?> key, Object value) {
Entry[] tab = table;
int len = tab.length;
//计算key在数据table的下标 这是是ThreadLocal的hashCode和长度-1取余
int i = key.threadLocalHashCode & (len-1);
//查看i索引位置有没有值,有值的话,索引位置+1,直到找到没有值的位置
for (Entry e = tab[i];
e != null;
//nextIndex在不超过数组长度索引值+1 超过则从0开始
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get();
//找到内存地址一样的ThreadLocal,则替换
if (k == key) {
e.value = value;
return;
}
//因为ThreadLocal为weakReference所以当无引用便会清理掉,这里直接替换
if (k == null) {
replaceStaleEntry(key, value, i);
return;
}
}‘
//当前i位置是无值的,存入threadlocal
tab[i] = new Entry(key, value);
int sz = ++size;
//当数组大小等于扩容阈值(数组大小的三分之二),进行扩容
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
set方法使用的冲突策略,也将对get方法产生影响
public T get() {
//获取当前线程
Thread t = Thread.currentThread();
//从当前线程取出ThreadLocalMap
ThreadLocalMap map = getMap(t);
if (map != null) {
//set的策略不同导致get策略也不同
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {//如果不为空,读取ThreadLocal中保存的值
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
//否则给当前线程ThreadLocal初始化 并返回null
return setInitialValue();
}
private Entry getEntry(ThreadLocal<?> key) {
//和set方法取索引值相同
int i = key.threadLocalHashCode & (table.length - 1);
Entry e = table[i];
//ThreadLocal的内存地址相同则返回,否则getEntryAfterMiss继续查找
if (e != null && e.get() == key)
return e;
else
return getEntryAfterMiss(key, i, e);
}
private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
Entry[] tab = table;
int len = tab.length;
while (e != null) {
ThreadLocal<?> k = e.get();
if (k == key) //内存地址一样,找到了
return e;
if (k == null) //删除没用的key
expungeStaleEntry(i);
else //索引位置 + 1
i = nextIndex(i, len);
e = tab[i];
}
return null;
}
最后在看下扩容逻辑
private void resize() {
Entry[] oldTab = table;
int oldLen = oldTab.length;
//新数组大小为老数组的两倍
int newLen = oldLen * 2;
Entry[] newTab = new Entry[newLen];
int count = 0;
//老数组的值拷贝到新数组上
for (int j = 0; j < oldLen; ++j) {
Entry e = oldTab[j];
if (e != null) {
ThreadLocal<?> k = e.get();
if (k == null) {
e.value = null; // Help the GC
} else {
//计算ThreadLocal在新数组中的位置
int h = k.threadLocalHashCode & (newLen - 1);
//如果索引值h的位置不为空,则往后继续寻找,直到找到为空的索引位置
while (newTab[h] != null)
h = nextIndex(h, newLen);
newTab[h] = e;
count++;
}
}
}
//给新数组初始化下次初始化的阈值,为数组长度的三分之二
setThreshold(newLen);
size = count;
table = newTab;
}
总结
通过学习get到
- ThreadLocal如何实现线程之间数据隔离
- inheritableThreadLocals和threadLocals初始化时机
- ThreadLocal为弱引用 当没有引用的时候会直接回收
- ThreadLocalMap类初始化大小为16 大于数组三分之二便进行扩容,扩容为原来的两倍