用法
- 隔离各个线程间的数据
- 避免线程内每个方法都进行传参,线程内的所有方法都可以直接获取到
ThreadLocal
中管理的对象。
package com.example.test1.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class AsyncTest {
// 使用threadlocal管理
private static final ThreadLocal<SimpleDateFormat> dateFormatLocal =
ThreadLocal.withInitial(( -> new SimpleDateFormat("yyyy-MM-dd";
// 不用threadlocal进行管理,用于对比
SimpleDateFormat dateFormat = new SimpleDateFormat(;
// 线程名称以task开头
@Async("taskExecutor"
public void formatDateSync(String format, Date date throws InterruptedException {
SimpleDateFormat simpleDateFormat = dateFormatLocal.get(;
simpleDateFormat.applyPattern(format;
// 所有方法都可以直接使用这个变量,而不用根据形参传入
doSomething(;
Thread.sleep(1000;
System.out.println("sync " + Thread.currentThread(.getName( + " | " + simpleDateFormat.format(date;
// 线程执行完毕,清除数据
dateFormatLocal.remove(;
}
// 线程名称以task2开头
@Async("taskExecutor2"
public void formatDate(String format, Date date throws InterruptedException {
dateFormat.applyPattern(format;
Thread.sleep(1000;
System.out.println("normal " + Thread.currentThread(.getName( + " | " + dateFormat.format(date;
}
}
使用junit
进行测试:
@Test
void test2( throws InterruptedException {
for(int index = 1; index <= 10; ++index{
String format = index + "-yyyy-MM-dd";
Date time = new Date(;
asyncTest.formatDate(format, time;
}
for(int index = 1; index <= 10; ++index{
String format = index + "-yyyy-MM-dd";
Date time = new Date(;
asyncTest.formatDateSync(format, time;
}
}
结果如下,可以看到没有被 ThreadLocal
管理的变量已经无法匹配正确的format。
sync task--10 | 10-2023-04-11
sync task--9 | 9-2023-04-11
normal task2-3 | 2-2023-04-11
normal task2-5 | 2-2023-04-11
normal task2-10 | 2-2023-04-11
normal task2-6 | 2-2023-04-11
sync task--1 | 1-2023-04-11
normal task2-7 | 2-2023-04-11
normal task2-8 | 2-2023-04-11
normal task2-9 | 2-2023-04-11
sync task--6 | 6-2023-04-11
sync task--3 | 3-2023-04-11
sync task--2 | 2-2023-04-11
sync task--7 | 7-2023-04-11
sync task--4 | 4-2023-04-11
sync task--8 | 8-2023-04-11
normal task2-4 | 2-2023-04-11
normal task2-1 | 2-2023-04-11
sync task--5 | 5-2023-04-11
normal task2-2 | 2-2023-04-11
实现原理
从ThreadLocal
中获取数据的过程:
- 先获取对应的线程。
- 通过
getMap(t
拿到线程中的ThreadLocalMap
-
ThreadLocalMap
是一个重新实现的散列表,基于两个元素实现散列:- 用户定义的
ThreadLocal
对象,例如:dateFormatLocal
。 - 封装了
value
的Entry
对象。
- 用户定义的
- 通过
map.getEntry(this
方法,根据当前的threadlocal
对象在散列表中获得对应的Entry
- 如果是第一次使用
get(
,则使用setInitialValue(
调用用户重写的initialValue(
方法创建map并使用用户指定的值初始化。
ThreadLocalMap会被销毁。
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 = (Te.value;
return result;
}
}
return setInitialValue(;
}
注意 Entry
对象是弱引用:
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
// k: ThreadLocal, v: value
Entry(ThreadLocal<?> k, Object v {
super(k;
value = v;
}
}
弱引用的常见用法是:
WeakReference<RoleDTO> weakReference = new WeakReference<>(new RoleDTO(;
因此,在Entry
中,k
代表ThreadLocal
对象,它是弱引用。v代表ThreadLocal
管理的那个value
,是强引用。
内存泄漏
内存泄漏是指无用对象(不再使用的对象)持续占有内存或无用对象的内存得不到及时释放,从而造成内存空间的浪费称为内存泄漏。随着垃圾回收器活动的增加以及内存占用的不断增加,程序性能会逐渐表现出来下降,极端情况下,会引发
OutOfMemoryError
导致程序崩溃。
ThreadLocal对象,这些对象的ThreadLocal
会保存在线程的ThreadLocalMap
中,因此ThreadLocalMap
会越来越大。
ThreadLocal是由任务(worker)传入的,一个任务执行结束后,对应的ThreadLocal
对象会被销毁。线程中的关系是: Thread -> ThreadLoalMap -> Entry<ThreadLocal, Object>
。ThreadLocal
由于是弱引用会,在GC的时候会被销毁,这会导致 ThreadLoalMap
中存在Entry<null, Object>
。
使用remove(
ThreadLoalMap进行清理,那Entry<null, Object>
会一直占用内存。remove(
方法会清除key==null
的Entry
。
使用static修饰
ThreadLocal设置成static
可以避免一个线程类多次传入线程池后重复创建Entry
。例如,有一个用户定义的线程
public class Test implements Runnable{
private static ThreadLocal<Integer> local = new ThreadLocal<>(;
@Override
public void run( {
// do something
}
}
使用线程池处理10个任务。那么线程池中每个用来处理任务的线程的Thread.ThreadLocalMap
中都会保存一个Entry<local, Integer>
,由于添加了static
关键字,所有每个线程中的Entry
中的local
变量引用的都是同一个变量。这时就算发生内存泄漏,所有的Test类也只有一个local
对象,不会导致内存占用过多。
@Test
void contextLoads( {
Runnable runnable = ( -> {
System.out.println(Thread.currentThread(.getName(;
};
for(int index = 1; index <= 10; ++index{
taskExecutor2.submit(new com.example.test1.service.Test(;
}
}