1、ThreadLocal基本介绍
ThreadLocal即变量副本,在多线程中,每个线程保存一个线程的本地变量副本,在使用中各用各的,避免共享资源的竞争;
从这里我们可以了解到变量副本会给每个线程一个变量值,是一种时间换空间的方案; 同时因为每个线程之间的操作相互不同步,不共享;因此变量副本仅适用于每个线程独立操作的场景;比如:存放session这种特征值,模板方法中不同实现的配置内容;
2、数据结构Entry
ThreadLocal的实现依赖于threadLocalMap,threadLocalMap是一个静态内部类;
static class ThreadLocalMap {
static class Entry extends WeakReference<ThreadLocal<?>> {
/** 与此ThreadLocal关联的值。key为当前的ThreadLocal, WeakReference 弱引用*/
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
/**
* 初始容量-必须是2的N次幂
*/
private static final int INITIAL_CAPACITY = 16;
/**
* table数组表,扩容必须2倍
*/
private Entry[] table;
/**
* 表中条目数量
*/
private int size = 0;
/**
* 要调整大小的下一个大小值
*/
private int threshold; // Default to 0
}
数据结构核心点:
1,threadLocal变量赋值:其实就是往threadLocalMap里面添加一个键值对,这个键值对以threadLocal为key,任意对象为value;
2,threadLocalMap中的键值对的key为弱引用,这就会造成内存泄露,在threadLocal外部强引用被置为null的时候key就会回收变为null,如果当前线程一直不结束(比如线程池复用线程)那么Entry中的value因为存在强引用链,会导致value一直无法回收,造成内存泄露;而使用弱引用的原因是,使用强引用会因为key无法被删除导致数据无法被清理;
==》最佳实践:因为有以上的问题,我们需要在程序中做好控制来避免内存泄露
每次使用完ThreadLocal,都调用它的remove()方法,清除数据。在使用线程池的情况下,没有及时清理ThreadLocal,不仅是内存泄漏的问题,更严重的是可能导致业务逻辑出现问题。所以,使用ThreadLocal就跟加锁完要解锁一样,用完就清理。
3,threadLocalMap和其他HashMap一样采用散列表进行数据存储,而这里比较特别的是解决三列冲突的方法选择上,threadLocalMap使用的是开放定址,即当发生hash冲突的时候,尝试在数组中寻找其他空的单元存储数据; 而hashMap,concurrentHashMap采用的是分离链表法-拉链法,即通过链表的方式解决hash冲突;
为什么要使用开放定址法? 在threadLocalMap中散列值分散的十分均匀,很少出现冲突;且经常需要清除无用的对象,使用纯数组更加方便。
3、常用操作
主要API:
/**
*用来获取当前线程在threadLocal中保存的当前线程的变量副本
*/
public T get() { }
/**
*用来设置当前线程的变量副本。将当前线程变量的副本设置到threadLocal中
*/
public void set(T value) { }
/**
*用来移除当前线程在Threadlocal存储的变量副本
*/
public void remove() { }
/**
*一般是用来在使用时进行重写的,它是一个延迟加载方法。给当前线程初始化一个初始值
*/
protected T initialValue() { }
操作demo
//使用案例:获取每个请求线程中的用户信息,
public class ThreadContext {
private static ThreadLocal<String> userResurece = new ThreadLocal<>();
public static String getUser() {
return userResurece.get(); //获取
}
public static void bindUser(String user) {
userResurece.set(user); //设置
}
public static String unbindUser() {
String user = userResurece.get();
userResurece.remove(); //移除
return user;
}
}
public class PerFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
try {
String user = ThreadContext.getUser();
if (user == null) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Object object = authentication.getPrincipal();
if (object != null) {
UserEntity userEntity = (UserEntity) object;
String value = org.apache.commons.lang3.RandomStringUtils.randomAlphabetic(5);
System.out.println(userEntity.getUuid()+"----"+Thread.currentThread().getName()+ value);
ThreadContext.bindUser(userEntity.getUsername()+"----"+Thread.currentThread().getName()+value);
}else {
ThreadContext.bindUser("testtestUser");
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
} finally {
// ThreadContext.unbindUser();
}
}
}
private String getUser() {
/* Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserEntity userEntity = (UserEntity) authentication.getPrincipal();*/
return ThreadContext.getUser();
}
4、源码分析
set()
private void set(ThreadLocal<?> key, Object value) {
Entry[] tab = table;
int len = tab.length;
//threadLocalHashCode 保证hash表的每个散列桶能够均匀分布;
//根据threadLocal的hashCode确定Entry应该存放的下标位置
int i = key.threadLocalHashCode & (len-1);
//采用开放地址法,hash冲突的时候使用nextIndex(i, len) 进行线性探测,是一个环形
for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get();
//覆盖旧Entry
if (k == key) {
e.value = value;
return;
}
//当key为null时,说明threadLocal强引用已经被释放掉,那么就无法
//再通过这个key获取threadLocalMap中对应的entry,这里就存在内存泄漏的可能性
if (k == null) {
//用当前插入的值替换掉key为null的“脏”entry
replaceStaleEntry(key, value, i);
return;
}
}
//新建entry并插入table中i处
tab[i] = new Entry(key, value);
int sz = ++size;
//插入后再次清除key为null的“脏”entry,
//如果大于阈值就需要扩容
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
//扩容因子设置
private void setThreshold(int len) {
threshold = len * 2 / 3;
}
//重点:扩容逻辑
private void resize() {
Entry[] oldTab = table;
int oldLen = oldTab.length;
//新数组为原数组的2倍
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();
//遍历过程中如果遇到脏entry的话直接另value为null,有助于value能够被回收
if (k == null) {
e.value = null; // Help the GC
} else {
//重新确定entry在新数组的位置,然后进行插入
int h = k.threadLocalHashCode & (newLen - 1);
while (newTab[h] != null)
h = nextIndex(h, newLen);
newTab[h] = e;
count++;
}
}
}
//设置新哈希表的threshHold和size属性
setThreshold(newLen);
size = count;
table = newTab;
}
get()
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t); //获取ThreadLocalMap:t.threadLocals; 当前线程的属性threadLocals指向ThreadLocalMap
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this); //重点1:获取数据key值对应的value
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue(); //重点2:map== null 或者entry == null 初始化值
}
//重点1:查询Map中保存的数据
private Entry getEntry(ThreadLocal<?> key) {
//1. 确定在散列数组中的位置
int i = key.threadLocalHashCode & (table.length - 1);
//2. 根据索引i获取entry
Entry e = table[i];
//3. 满足条件则返回该entry
if (e != null && e.get() == key)
return e;
else
//4. 未查找到满足条件的entry,即存在hash冲突的情况下的处理
return getEntryAfterMiss(key, i, e);
}
//重点1-2:hash冲突情况下的处理
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)
//找到和查询的key相同的entry则返回
return e;
if (k == null)
//解决脏entry的问题
expungeStaleEntry(i);
else
//继续向后环形查找
i = nextIndex(i, len);
e = tab[i];
}
return null;
}
//重点2 设置初始化值并返回
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;
}
//可以通过子类实现,给不同的默认值
protected T initialValue() {
return null;
}
remove()
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) {
//将entry的key置为null
e.clear();
//将该entry的value也置为null
expungeStaleEntry(i);
return;
}
}
}