用法
- 隔离各个线程间的数据
- 避免线程内每个方法都进行传参,线程内的所有方法都可以直接获取到
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 = (T)e.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, Ob