简单介绍下 ThreadLocal
本文详细解析了 ThreadLocal 的核心概念、实现原理、优缺点与典
简介
ThreadLocal 是Java中一个非常重要的线程技术。它可以让每个线程都拥有自己的变量副本,避免了线程间的竞争和数据泄露问题。在本文中,我们将详细介绍 ThreadLocal 的定义、用法及其优点。
ThreadLocal 是Java中一个用来实现线程封闭技术的类。它提供了一个本地线程变量,可以在多线程环境下使每个线程都拥有自己的变量副本。每个线程都可以独立地改变自己的副本,而不会影响到其他线程的副本。ThreadLocal 的实现是基于 ThreadLocalMap 的,每个 ThreadLocal 对象都对应一个 ThreadLocalMap,其中存储了线程本地变量的值。
优缺点
ThreadLocal 的主要优点是可以提高并发程序的性能和安全性,同时也存在一些缺点和使用场景需要注意。
优点:
- 提高并发性能:使用 ThreadLocal 可以避免多个线程之间的竞争,从而提高程序的并发性能。
- 保证线程安全:每个线程有自己独立的变量副本,避免了线程安全问题。
- 简化代码:使用 ThreadLocal 可以避免传递参数的繁琐,简化代码。
缺点:
- 内存泄漏:ThreadLocal 变量副本的生命周期与线程的生命周期一样长,如果线程长时间存在,而 ThreadLocal 变量没有及时清理,就会造成内存泄漏。
- 增加资源开销:每个线程都要创建一个独立的变量副本,如果线程数很多,就会增加资源开销。
- 不适用于共享变量:ThreadLocal 适用于每个线程有独立的变量副本的场景,不适用于共享变量的场景。
适用场景
- 线程安全的对象:ThreadLocal 适用于需要在多个线程中使用的线程安全对象,例如 SimpleDateFormat、Random 等。
- 跨层传递参数:ThreadLocal 可以避免在方法之间传递参数的繁琐,尤其在跨层传递参数的场景中,可以大大简化代码(如:
Interceptor(userId) => Controller(userId) => Service(userId))。 - 线程局部变量:ThreadLocal 可以用于在当前线程中存储和访问局部变量,例如日志、请求信息等。
实现原来
我们通过 Idea 查看 ThreadLocal 与线程的关系图:

- 每个 Thread 对象都有一个 ThreadLocalMap 类型的成员变量threadLocals,这个变量是一个键值对集合,用于存储每个ThreadLocal对象对应的值。
java
public
class Thread implements Runnable {
...
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
}
- 每个
ThreadLocal对象都有一个唯一的 ID,用于在ThreadLocalMap中作为键来存储值。
java
public class ThreadLocal<T> {
/**
* ThreadLocals rely on per-thread linear-probe hash maps attached
* to each thread (Thread.threadLocals and
* inheritableThreadLocals). The ThreadLocal objects act as keys,
* searched via threadLocalHashCode. This is a custom hash code
* (useful only within ThreadLocalMaps) that eliminates collisions
* in the common case where consecutively constructed ThreadLocals
* are used by the same threads, while remaining well-behaved in
* less common cases.
*/
private final int threadLocalHashCode = nextHashCode();
/**
* The next hash code to be given out. Updated atomically. Starts at
* zero.
*/
private static AtomicInteger nextHashCode =
new AtomicInteger();
/**
* The difference between successively generated hash codes - turns
* implicit sequential thread-local IDs into near-optimally spread
* multiplicative hash values for power-of-two-sized tables.
*/
private static final int HASH_INCREMENT = 0x61c88647;
/**
* Returns the next hash code.
*/
private static int nextHashCode() {
return nextHashCode.getAndAdd(HASH_INCREMENT);
}
- 当一个线程第一次调用
ThreadLocal对象的get()方法时,它会先获取当前线程的ThreadLocalMap对象,然后以 ThreadLocal 对象的 ID 作为键,从ThreadLocalMap中获取对应的值。
java
/**
* Returns the value in the current thread's copy of this
* thread-local variable. If the variable has no value for the
* current thread, it is first initialized to the value returned
* by an invocation of the {@link #initialValue} method.
*
* @return the current thread's value of this thread-local
*/
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();
}
/**
* Variant of set() to establish initialValue. Used instead
* of set() in case user has overridden the set() method.
*
* @return the initial value
*/
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);
}
if (this instanceof TerminatingThreadLocal) {
TerminatingThreadLocal.register((TerminatingThreadLocal<?>) this);
}
return value;
}
/**
* Create the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @param firstValue value for the initial entry of the map
*/
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
static class ThreadLocalMap {
/**
* Construct a new map initially containing (firstKey, firstValue).
* ThreadLocalMaps are constructed lazily, so we only create
* one when we have at least one entry to put in it.
*/
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
}
- 如果
ThreadLocalMap中不存在对应的键值对,则调用ThreadLocal对象的initialValue()方法来初始化一个值,并将其存储到 ThreadLocalMap 中。 - 如果
ThreadLocalMap对象的引用不再需要,那么需要手动将其置为 null,这样可以避免内存泄漏。
内存泄漏
ThreadLocal 变量副本的生命周期与线程的生命周期一样长,如果线程长时间存在,而 ThreadLocal 变量没有及时清理,就会造成内存泄漏。为了避免内存泄漏,可以在使用 ThreadLocal 的地方及时清理 ThreadLocal 变量,例如在线程池中使用 ThreadLocal 时,需要在线程结束时手动清理 ThreadLocal 变量。
原因:
ThreadLocalMap 中的 Entry 对象持有 ThreadLocal 对象的弱引用,但是 ThreadLocalMap 中的 Entry 对象是由 ThreadLocal 对象强引用的。如果 ThreadLocal 对象没有及时清理,在 ThreadLocal 对象被垃圾回收时,ThreadLocalMap 中的 Entry 对象仍然存在,从而导致内存泄漏。
解决
在使用 ThreadLocal 的代码中及时清理 ThreadLocal 变量。通常情况下,我们可以使用 ThreadLocal 的 remove() 方法手动清理 ThreadLocal 变量,或者在使用完ThreadLocal变量后将其设置为 null。

通过上图我们可以看到,在线程方法执行过程中,ThreadLocal、ThreadLocalMap 以及 Thread 之间的引用关系; Thread 中存在一个属性 threadLocals 指向了 ThreadLocalMap,ThreadLocal 实现线程级别的数据隔离主要是基于该对象;在 ThreadLocal 中是没有存储任何数据,其更像一个线程与 ThreadLocalMap 间的协调器,数据存储在 ThreadLocalMap 中,但是该 Map 的 Key 却是 ThreadLocal 的弱引用。
一般情况下,线程执行完成后,待线程销毁,那么线程对应的属性 threadLocals 也会被销毁;但是真实环境中对线程的使用大部分都是线程池,这样在整个系统生命周期中,线程都是有效的,直至线程池关闭。而将ThreadLocalMap 的 Key 设置成弱引用时,经过 GC 后该 Map 的 Key 则变成了 null,但是其 Value 却一直存在,因此需要手动将 key 为 null 的数据进行清理。
demo代码
这里我演示下如何避免 ThreadLocal 的内存泄漏
java
package com.salmon.demo;
import com.salmon.demo.model.User;
/**
* 用户上下文持有者
* @author Salmon
* @since 2024-05-25
*/
public class UserHolder {
private static final ThreadLocal<User> threadLocal = new ThreadLocal<>();
public static void set(User user) {
threadLocal.set(user);
}
public static User get() {
return threadLocal.get();
}
public static void remove() {
threadLocal.remove();
}
}
/**
* 测试
*/
class ThreadLocalTest{
public static void main(String[] args) {
User user=new User();
user.setId(1L);
user.setName("Salmon");
UserHolder.set(user);
System.out.println(UserHolder.get());
// 在使用完 ThreadLocal 变量后,调用 remove() 方法清理 ThreadLocal 变量
UserHolder.remove();
}
}
线程数据隔离
下面是一个简单的例子,演示如何使用 ThreadLocal 来实现线程数据隔离:
java
package com.salmon.demo;
import com.salmon.demo.model.User;
/**
* 用户上下文持有者
*
* @author Salmon
* @since 2024-05-25
*/
public class UserHolder {
private static final ThreadLocal<User> threadLocal = new ThreadLocal<>();
public static void set(User user) {
threadLocal.set(user);
}
public static User get() {
return threadLocal.get();
}
public static void remove() {
threadLocal.remove();
}
}
/**
* 测试
*/
class ThreadLocalTest {
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
User user = new User();
user.setId(1L);
user.setName("Salmon");
UserHolder.set(user);
System.out.println("Thread A: " + UserHolder.get());
}).start();
new Thread(() -> {
User user = new User();
user.setId(2L);
user.setName("薛之谦");
UserHolder.set(user);
System.out.println("Thread B: " + UserHolder.get());
}).start();
Thread.sleep(1000);
System.out.println("Main: " + UserHolder.get());
}
}
运行结果如下:

从输出结果可以看出,每个线程都拥有自己的变量副本,互不影响。而在主线程中,由于没有设置过变量副本,所以返回 null。
结语
ThreadLocal 是帮助我们在多个线程间实现线程对数据的独享,而不是用来解决线程间的数据共享问题。