ThreadLocal分析
<h1 id="threadlocal">ThreadLocal</h1><p><strong>本文以JDK21为例子,其实大致方法和JDK8都一样。</strong></p>
<h2 id="1基本介绍">1.基本介绍</h2>
<p><code>ThreadLocal</code> 是一个在多线程编程中常用的概念,不同编程语言中实现方式不同,但核心思想一致:<strong>为每个使用该变量的线程都提供一个独立的变量副本</strong>,每个线程都可以独立地改变自己的副本,而不会影响其他线程所对应的副本。</p>
<p><strong>主要作用</strong></p>
<ol>
<li><strong>线程安全</strong>:避免多线程共享变量时需要进行同步操作(如加锁),从而简化并发编程。</li>
<li><strong>传递上下文</strong>:在同一个线程的不同方法中传递数据,避免显式传递参数。</li>
</ol>
<p>它的几个API:</p>
<table>
<thead>
<tr>
<th>方法声明</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>ThreadLocal()</td>
<td>创建ThreadLocal对象</td>
</tr>
<tr>
<td>public void set(T value)</td>
<td>设置当前线程绑定的局部变量</td>
</tr>
<tr>
<td>public T get()</td>
<td>获取当前线程绑定的局部变量</td>
</tr>
<tr>
<td>public void remove()</td>
<td>移除当前线程绑定的局部变量</td>
</tr>
</tbody>
</table>
<p>下面来简单使用一下:</p>
<pre><code class="language-java">public class SimpleLocalTest {
private static ThreadLocal<String> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
threadLocal.set("main" + "变量");
new Thread(() -> {
// 在线程1中设置变量
threadLocal.set("thread1" + "变量");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 在线程1中得到的仍然是该变量的值,并没有得到其他线程的值,达到了线程间数据隔离
System.out.println(Thread.currentThread().getName() + " : " + threadLocal.get());
threadLocal.remove(); // 删除掉
}, "线程1").start();
new Thread(() -> {
threadLocal.set("thread2" + "变量"); // 同理
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " : " + threadLocal.get());
threadLocal.remove();
}, "线程2").start();
// 主线程的本地变量值
System.out.println(Thread.currentThread().getName() + " : " + threadLocal.get());
threadLocal.remove();
}
}
</code></pre>
<h2 id="2对比synchronized">2.对比Synchronized</h2>
<p><code>ThreadLocal</code> 和 <code>Synchronized</code>(或其他同步机制)都用于处理多线程环境下的并发问题,但它们的核心思路和应用场景完全不同。</p>
<table>
<thead>
<tr>
<th style="text-align: left"><strong>ThreadLocal</strong></th>
<th style="text-align: left"><strong>Synchronized</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left"><strong>避免共享</strong>:为每个线程创建独立的变量副本,线程之间互不干扰。</td>
<td style="text-align: left"><strong>控制共享</strong>:通过锁机制保证多线程对共享资源的<strong>有序访问</strong>。</td>
</tr>
<tr>
<td style="text-align: left"><strong>空间换时间</strong>:每个线程单独存储数据,牺牲内存换取无锁的高效。</td>
<td style="text-align: left"><strong>时间换空间</strong>:通过阻塞其他线程的访问,保证共享资源的安全性。</td>
</tr>
<tr>
<td style="text-align: left">每个线程内部通过 <code>ThreadLocalMap</code> 存储自己的变量副本,键是 <code>ThreadLocal</code> 对象,值是变量值。</td>
<td style="text-align: left">基于 JVM 内置锁(Monitor)实现,通过锁的获取和释放控制代码块或方法的访问权限。</td>
</tr>
<tr>
<td style="text-align: left">通过 <code>get()</code>/<code>set()</code> 直接操作当前线程的局部变量,无需锁。</td>
<td style="text-align: left">锁竞争时,未获取锁的线程会进入阻塞状态(或自旋),直到锁释放。</td>
</tr>
<tr>
<td style="text-align: left"><strong>线程隔离</strong>:每个线程需要独立操作变量(如用户会话、数据库连接)。</td>
<td style="text-align: left"><strong>共享资源保护</strong>:多个线程需要操作同一资源(如计数器、缓存)。</td>
</tr>
<tr>
<td style="text-align: left"><strong>避免线程安全问题</strong>:通过隔离变量副本,无需同步(如 <code>SimpleDateFormat</code>)。</td>
<td style="text-align: left"><strong>原子性保证</strong>:确保一段代码的原子执行(如余额扣减)。</td>
</tr>
<tr>
<td style="text-align: left"><strong>性能敏感场景</strong>:避免锁竞争的开销(如线程池中的上下文传递)。</td>
<td style="text-align: left"><strong>临界区保护</strong>:保护共享数据的读写一致性。</td>
</tr>
<tr>
<td style="text-align: left"><strong>内存泄漏风险</strong>:若未调用 <code>remove()</code>,线程池中的线程可能因 <code>ThreadLocalMap</code> 的强引用导致内存泄漏。</td>
<td style="text-align: left"><strong>性能开销</strong>:锁竞争激烈时,线程阻塞和唤醒会带来性能损耗(尤其是重量级锁)。</td>
</tr>
<tr>
<td style="text-align: left"><strong>无锁操作</strong>:<code>get()</code>/<code>set()</code> 直接操作线程私有数据,性能极高。</td>
<td style="text-align: left"><strong>锁优化</strong>:JVM 对 <code>synchronized</code> 有锁升级机制(偏向锁→轻量级锁→重量级锁)。</td>
</tr>
</tbody>
</table>
<ul>
<li>两者可以结合使用:例如用 <code>ThreadLocal</code> 保存线程私有数据【数据隔离】,用 <code>Synchronized</code> 保护共享状态【数据共享】。</li>
<li>现代框架中的典型应用:Spring 的事务管理通过 <code>ThreadLocal</code> 保存数据库连接</li>
</ul>
<h2 id="3原理分析">3.原理分析</h2>
<p>首先从上面的ThreadLocal简单使用案例的方法来看看。</p>
<h3 id="set">①set</h3>
<pre><code class="language-java">// 首先是构造方法
public ThreadLocal() {} // 没啥好看的
// 然后是set方法
public void set(T value) {
//public static native Thread currentThread();这是个native方法
//currentThread方法返回正在被执行的线程的信息。
set(Thread.currentThread(), value);
if (TRACE_VTHREAD_LOCALS) { // 这个就不用看了
dumpStackIfVirtualThread();
}
}
private void set(Thread t, T value) {
ThreadLocalMap map = getMap(t); // 调用getMap方法
if (map != null) {
// key 是Thread
map.set(this, value); // 如果map不是null,就把kv设置进去
} else {
// 创建map
createMap(t, value);
}
}
// 返回Thread的threadLocals变量
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
void createMap(Thread t, T firstValue) {
// 把Thread的这个变量初始化
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
// ThreadLocalMap的构造方法
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
// 初始化哈希表,然后把第一个kv放进去
table = new Entry;
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
</code></pre>
<p>经过上面的源码分析我们可以得出以下信息:</p>
<ul>
<li>每个Thread对象里面都有一个threadLocals变量,它的类型是ThreadLocalMap;</li>
<li>ThreadLocalMap是ThreadLocal的静态内部类</li>
</ul>
<p>下面来简单看一下ThreadLocalMap(ThreadLocal的静态内部类)</p>
<pre><code class="language-java">static class ThreadLocalMap {
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
private static final int INITIAL_CAPACITY = 16;
private Entry[] table;
private int size = 0;
private int threshold;
// set
// getEntry【返回hash索引位置上的对象Entry】
private Entry getEntry(ThreadLocal<?> key) {
int i = key.threadLocalHashCode & (table.length - 1);
Entry e = table;
if (e != null && e.refersTo(key))
return e;
else
return getEntryAfterMiss(key, i, e);
}
.......
}
</code></pre>
<p>可以把它看作为一个Map。到这里,set方法算是知道了,然后还大致知道了他们之间的关系,如下图:【不同线程之间的ThreadLocal他们的value是不一样的,达到了线程隔离的效果】</p>
<p><img src="https://img2023.cnblogs.com/blog/2358057/202505/2358057-20250512170621655-1303683455.png" alt="" loading="lazy"></p>
<h3 id="get">②get</h3>
<pre><code class="language-java">public T get() {
return get(Thread.currentThread());
}
private T get(Thread t) {
//getMap在面已经知道了
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;
}
}
// 如果t.threadLocals == null
return setInitialValue(t);
}
// 初始化
private T setInitialValue(Thread t) {
T value = initialValue(); // 调用这个
ThreadLocalMap map = getMap(t);
if (map != null) {
map.set(this, value);
} else {
createMap(t, value);
}
if (this instanceof TerminatingThreadLocal<?> ttl) {
TerminatingThreadLocal.register(ttl);
}
if (TRACE_VTHREAD_LOCALS) {
dumpStackIfVirtualThread();
}
return value;
}
/*
此方法的作用是返回该线程局部变量的初始值。
- 这个方法是一个延迟调用方法,从上面的代码我们得知,在set方法还未调用而先调用了get方法时才执行,并且仅执行1次。
- 这个方法直接返回一个null。
- 如果想要一个除null之外的初始值,可以重写此方法。(该方法是一个protected的方法,显然是为了让子类覆盖而设计的)
*/
protected T initialValue() {
return null;
}
</code></pre>
<p>get方法就是首先拿到执行方法的线程是哪一个,然后从该线程的threadLocals(ThreadLocalMap)上以该Thread对象为key,拿到Entry的value值。</p>
<h3 id="remove">③remove</h3>
<pre><code class="language-java">public void remove() {
remove(Thread.currentThread());
}
private void remove(Thread t) {
ThreadLocalMap m = getMap(t);
if (m != null) {
// 实际是ThreadLocalMap的remove方法
m.remove(this);
}
}
// 静态内部类ThreadLocalMap.java
private void remove(ThreadLocal<?> key) {
Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);
for (Entry e = tab;
e != null;
e = tab) {
if (e.refersTo(key)) {
e.clear();
expungeStaleEntry(i);
return;
}
}
}
// 会调用这个
/*
主要用于清理因弱引用导致key为null 的过期Entry,从而避免内存泄漏-见下文
*/
private int expungeStaleEntry(int staleSlot) {
。。。。
}
</code></pre>
<p>直接将ThrealLocal 对应的值从当前的Thread中的ThreadLocalMap中删除</p>
<h3 id="再说threadlocalmap">④再说ThreadLocalMap</h3>
<p>我们对于ThreadLocal的get、set或者是remove,本质上都是在操作ThreadLocaMap里面的Entry数组</p>
<pre><code class="language-java">static class ThreadLocalMap {
static class Entry extends WeakReference<ThreadLocal<?>> {
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
}
</code></pre>
<p>Entry将ThreadLocal作为Key【<strong>为弱引用</strong>】,值作为value保存,它继承自WeakReference. 这个弱引用是啥?前面还说了,可以把它看作为一个Map(ThreadLocalMap并没有实现Map接口),但是我们熟知的HashMap之类的,key可能是会冲突的,这里的ThreadLocalMap里面的key冲突了咋办呢?本节就来分析一下。</p>
<h4 id="1-冲突">1) 冲突</h4>
<p><strong>发生冲突的时候</strong>,那么肯定是在set/get的时候把,我们看一下set方法</p>
<pre><code class="language-java">// 静态内部类ThreadLocalMap.java
private void set(ThreadLocal<?> key, Object value) {
Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);
/*
这里的nextIndex如下【说实话就是 i+1】
private static int nextIndex(int i, int len) {
return ((i + 1 < len) ? i + 1 : 0);
}
*/
for (Entry e = tab; e != null; e = tab) {
if (e.refersTo(key)) { // 如果key相同
e.value = value; // value直接覆盖
return;
}
//如果当前位置是空的,就初始化一个Entry对象放在位置i上
if (e.refersTo(null)) {
replaceStaleEntry(key, value, i);
return;
}
}
// 找到了下标为null的位置
tab = new Entry(key, value); // 这个位置设置上key,value
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
</code></pre>
<p>根据上面的源码分析,我们得知,set的时候,根据ThreadLocal对象的hash值,定位到table中的位置i,然后判断该位置是否为空;如果key相同,直接覆盖旧值;如果是空的,初始化一个Entry对象放在位置i上;否则,就在i的位置上,往后一个一个找。【<strong>线性探测法</strong>】</p>
<p>再来看一下get方法:</p>
<pre><code class="language-java">// 静态内部类ThreadLocalMap.java
private Entry getEntry(ThreadLocal<?> key) {
int i = key.threadLocalHashCode & (table.length - 1);
Entry e = table;
if (e != null && e.refersTo(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;
// 相等就直接返回,不相等就继续+1查找,找到相等为止。
while (e != null) {
if (e.refersTo(key))
return e;
if (e.refersTo(null))
expungeStaleEntry(i);
else
i = nextIndex(i, len);
e = tab;
}
return null;
}
</code></pre>
<p>上面的源码很简单吧。可以知道,ThreadLocal在hash冲突严重的时候,他的效率其实是不高的。</p>
<h4 id="2-弱引用">2) 弱引用</h4>
<p>那么这个<strong>弱引用</strong>呢?说起这个,肯定会提到ThreadLocal老生常谈的<strong>内存泄漏</strong>问题了。</p>
<blockquote>
<p>内存泄漏:【不会再被使用的对象或者变量占用的内存不能被回收,就是内存泄露。】</p>
<p>Memory overflow:内存溢出,没有足够的内存提供申请者使用。</p>
<p>Memory leak:内存泄漏是指程序中己动态分配的堆内存由于某种原因程序未释放或无法释放,造成系统内存的浪费,导致程序运行速度减慢甚至系统溃等严重后果。内存泄漏的堆积终将导致内存溢出。</p>
</blockquote>
<p>在 Java 中,<strong>弱引用(Weak Reference)</strong> 是一种特殊的引用类型,它的核心特点是:<strong>当垃圾回收(GC)发生时,无论内存是否充足,弱引用指向的对象【对象必须仅被弱引用指向(没有任何强引用)】都会被回收</strong>。这与其他引用类型(如强引用、软引用、虚引用)有显著区别。下面通过对比不同引用类型,详细解释弱引用的特性及用途。</p>
<table>
<thead>
<tr>
<th style="text-align: left"><strong>引用类型</strong></th>
<th style="text-align: left"><strong>GC 行为</strong></th>
<th style="text-align: left"><strong>典型应用场景</strong></th>
<th style="text-align: left"><strong>实现类</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left"><strong>强引用</strong></td>
<td style="text-align: left">对象有强引用时,永远不会被回收(<strong>如果想取消强引用和某个对象之间的关联,可以显式地将引用赋值为null,这样可以使JVM在合适的时间就会回收该对象。</strong>)</td>
<td style="text-align: left">日常对象的使用(如 <code>new Object()</code>)</td>
<td style="text-align: left">默认引用类型</td>
</tr>
<tr>
<td style="text-align: left"><strong>弱引用</strong></td>
<td style="text-align: left"><strong>只要发生 GC,就会被回收</strong></td>
<td style="text-align: left">缓存、<code>ThreadLocal</code> 防内存泄漏</td>
<td style="text-align: left"><code>WeakReference<T></code></td>
</tr>
<tr>
<td style="text-align: left">软引用</td>
<td style="text-align: left">内存不足时才会被回收</td>
<td style="text-align: left">缓存(如图片缓存)</td>
<td style="text-align: left"><code>SoftReference<T></code></td>
</tr>
<tr>
<td style="text-align: left">虚引用</td>
<td style="text-align: left">无法通过虚引用访问对象,GC 后会收到通知</td>
<td style="text-align: left">资源清理跟踪(如堆外内存释放)</td>
<td style="text-align: left"><code>PhantomReference<T></code></td>
</tr>
</tbody>
</table>
<p>弱引用的回收时机由 GC 决定,无法精确控制。</p>
<p>在弄清楚上述的内存泄漏和弱引用问题之前,我们需要先知道ThreadLocal体系的对象存在哪里的,如下图:</p>
<p><code>Thread ThreadRef = new Thread(xx);就是强引用,下图中用实线连接起来的,ThreadLocal同理。</code></p>
<p><img src="https://img2023.cnblogs.com/blog/2358057/202505/2358057-20250512170622511-517440564.png" alt="" loading="lazy"></p>
<p>在 <code>ThreadLocal</code> 的使用中,<strong>内存泄漏的核心原因是 <code>ThreadLocalMap</code> 的 Entry 对 value 是强引用,而 Entry 的 key 是对 <code>ThreadLocal</code> 实例的弱引用</strong>。当 <code>ThreadLocal</code> 实例失去外部强引用时,GC 会回收 key(弱引用),key就为null了,但 value 仍被强引用保留在 Entry 中,若线程长期存活(如线程池线程),value 将无法被回收,导致内存泄漏。那么,什么时候ThreadLocal会失去外部的强引用呢?下面给出两个例子</p>
<pre><code class="language-java">// 下面两个例子中,线程一直存活
// 1.局部变量场景
public void processRequest() {
ThreadLocal<User> userContext = new ThreadLocal<>(); // 局部变量
userContext.set(currentUser);
// ...业务逻辑...
}
// 另一个线程一直存活
Thread(() -> {
processRequest();
......
}).start();
/*
在上述场景中:
方法结束时,局部变量 userContext 的强引用被释放。
此时 ThreadLocal 实例仅被 ThreadLocalMap 的弱引用(Entry 的 key)指向。
下次 GC 发生时,ThreadLocal 实例的 key 被回收,Entry 变为 key=null, value=强引用。
若线程持续运行(如线程池线程),value 无法自动回收,导致泄漏。
*/
// 2.实例变量所属对象被回收
public class Service {
// 在这里,ThreadLocal作为了对象的实例变量
private ThreadLocal<Connection> connHolder = new ThreadLocal<>();
public void execute() {
connHolder.set(getConnection());
// ...使用连接...
}
}
// 使用示例
void process() {
Service service = new Service();
service.execute();
service = null; // Service 实例失去强引用,可能被回收
}
// 另一个线程一直存活
Thread(() -> {
process();
......
}).start();
</code></pre>
<p><strong>总结一下,何时出现 “无外部强引用”?</strong></p>
<ol>
<li><strong>当<code>ThreadLocal</code> 实例不再被任何强引用直接或间接指向的时候</strong>:
<ul>
<li>局部变量超出作用域。</li>
<li>所属对象实例被回收。</li>
</ul>
</li>
<li><strong>但线程仍存活</strong>(如线程池线程长期复用)。</li>
</ol>
<p>我们平时开发都是使用的线程池,线程有的可能会一直存活。</p>
<p>为了避免出现上述情况,我们平时使用完成之后,尽量<strong>在业务结束并且不需要该线程本地变量的时候,给它remove掉</strong>。</p>
<p>通过上述分析,我们可以看到一个非常致命的条件,那就是线程存活的时间 大于了 ThreadLocal的强引用存活时间。<strong>如果说,ThreadLocal 和 Thread的生命周期一样长,即时我们不remove,一样不会内存泄漏的。( 如下图 )</strong></p>
<p><img src="https://img2023.cnblogs.com/blog/2358057/202505/2358057-20250512170622952-1899538612.png" alt="" loading="lazy"></p>
<p>ThreadLocal其实它有兜底措施的:【就是上面的remove方法里面调用的<code>expungeStaleEntry</code>】</p>
<pre><code class="language-java">/*
在这些方法也会调用的
set()方法: 当插入新值时发现哈希冲突,且当前槽位的Entry已过期,触发清理流程
get()方法: 当查询Entry未命中(key 不匹配)时,触发清理以优化后续查询效率
*/
private int expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
// 清理当前槽位
tab.value = null;
tab = null;
size--;
// Rehash until we encounter null
Entry e;
int i;
for (i = nextIndex(staleSlot, len);
(e = tab) != null;
i = nextIndex(i, len)) {
ThreadLocal<?> k = e.get();
if (k == null) {// 清理过期 Entry
e.value = null;
tab = null;
size--;
} else {// 重新哈希有效 Entry
int h = k.threadLocalHashCode & (len - 1);
if (h != i) {
tab = null;
while (tab != null)
h = nextIndex(h, len);
tab = e;
}
}
}
return i;
}
</code></pre>
<p>当 <code>ThreadLocal</code> 实例被垃圾回收(GC)后,其对应的 <code>Entry</code> 的 <code>key</code> 会变为 <code>null</code>(弱引用特性),但 <code>value</code> 仍被强引用保留。<code>expungeStaleEntry</code> 会遍历哈希数组,将这些 <code>key</code> 为 <code>null</code> 的 <code>Entry</code> 的 <code>value</code> 置为 <code>null</code>,并释放 <code>Entry</code> 对象本身,从而切断 <code>value</code> 的强引用链,帮助 GC 回收内存</p>
<p>删除的时候:</p>
<ul>
<li>从指定位置开始向后遍历哈希数组,若发现 <code>Entry</code> 的 <code>key</code> 为 <code>null</code>,则清除其 <code>value</code> 并释放 <code>Entry</code> 对象。</li>
<li>若 <code>Entry</code> 的 <code>key</code> 有效,则重新计算其哈希值(<code>k.threadLocalHashCode & (len - 1)</code>),检查是否需要调整位置以优化哈希分布</li>
</ul>
<p>从上述分析可以看出:<code>expungeStaleEntry</code> 仅清理从指定位置开始的连续过期 <code>Entry</code>,而非整个哈希表,因此无法完全避免内存泄漏;清理效果取决于 <code>set</code>、<code>get</code> 等方法的调用频率,若线程长期不操作 <code>ThreadLocal</code>,残留的 <code>value</code> 仍可能堆积。</p>
<p>那<strong>如果key是强引用</strong>呢?会出现上述内存泄漏问题吗?</p>
<p><img src="https://img2023.cnblogs.com/blog/2358057/202505/2358057-20250512170623395-776007206.png" alt="" loading="lazy"></p>
<p>为什么key设计成弱引用呢?</p>
<p>当 <code>ThreadLocalMap</code> 的键是 <strong>弱引用</strong> 时:</p>
<ol>
<li>外部强引用 <code>threadLocal</code> 被置为 <code>null</code> 后,键(弱引用)指向的 <code>ThreadLocal</code> 对象仅被弱引用持有。</li>
<li><strong>GC 会回收 <code>ThreadLocal</code> 对象</strong>,并将对应的弱引用放入引用队列,key就为null了。</li>
<li><code>ThreadLocalMap</code> 在下次操作(如 <code>get()</code>、<code>set()</code>)时,会清理引用队列中的失效条目,释放值对象的内存。【就是我们说的兜底措施嘛】</li>
</ol>
<p>如果 <code>ThreadLocalMap</code> 的键是 <strong>强引用</strong>,会发生:</p>
<ol>
<li><code>threadLocal</code> 变量被置为 <code>null</code>,但 <code>ThreadLocalMap</code> 中的键仍强引用着 <code>ThreadLocal</code> 对象。</li>
<li><strong><code>ThreadLocal</code> 对象无法被 GC 回收</strong>,导致其对应的值(<code>BigObject</code>)也无法被回收,即使线程可能长期存活(如线程池中的线程)。</li>
<li><strong>内存泄漏</strong>:无用的键值对会一直存在于 <code>ThreadLocalMap</code> 中</li>
</ol>
<h2 id="5框架中的应用">5.框架中的应用</h2>
<p>这一节只看一下ThreadLocal在Spring事务中的应用。</p>
<p>在事务中,需要做到如下保证:</p>
<blockquote>
<ol>
<li>每个事务的执行需要通过数据源连接池获取到数据库的connetion。</li>
<li>为了保证所有的数据库操作都属于同一个事务,事务使用的连接必须是同一个,也就是在一个线程里面需要操作同一个连接</li>
<li>线程隔离:在多线程并发的情况下,每个线程都只能操作各自的connetion,不能使用其他线程的连接</li>
</ol>
</blockquote>
<p>在Spring事务的源码中:</p>
<p><code>DataSourceTransactionManager.java</code></p>
<pre><code class="language-java">@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
Connection con = null;
try {
if (!txObject.hasConnectionHolder() ||
txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
Connection newCon = obtainDataSource().getConnection();
...
txObject.setConnectionHolder(new ConnectionHolder(newCon), true);
}
txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
con = txObject.getConnectionHolder().getConnection();
....
// 手动开启一个事务
if (con.getAutoCommit()) {
txObject.setMustRestoreAutoCommit(true);
...
con.setAutoCommit(false);
}
prepareTransactionalConnection(con, definition);
txObject.getConnectionHolder().setTransactionActive(true);
int timeout = determineTimeout(definition);
if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
}
// Bind the connection holder to the thread.
if (txObject.isNewConnectionHolder()) {
TransactionSynchronizationManager.bindResource(obtainDataSource(), txObject.getConnectionHolder());
}
}
catch (Throwable ex) {
if (txObject.isNewConnectionHolder()) {
DataSourceUtils.releaseConnection(con, obtainDataSource());
txObject.setConnectionHolder(null, false);
}
throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", ex);
}
}
</code></pre>
<p><code>TransactionSynchronizationManager.java</code> :下面就把线程和ThreadLocal绑定起来了。</p>
<pre><code class="language-java">public abstract class TransactionSynchronizationManager {
private static final ThreadLocal<Map<Object, Object>> resources =
new NamedThreadLocal<>("Transactional resources");
....
public static void bindResource(Object key, Object value) throws IllegalStateException {
// 这个其实是数据源dataSource对象
Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);
Assert.notNull(value, "Value must not be null");
// 拿到当前线程的map
Map<Object, Object> map = resources.get();
// 为空,初始化一下
if (map == null) {
map = new HashMap<>();
resources.set(map);
}
Object oldValue = map.put(actualKey, value);
if (oldValue instanceof ResourceHolder && ((ResourceHolder) oldValue).isVoid()) {
oldValue = null;
}
if (oldValue != null) {
throw new IllegalStateException(
"Already value [" + oldValue + "] for key [" + actualKey + "] bound to thread");
}
}
// 清理remove操作
@Nullable
private static Object doUnbindResource(Object actualKey) {
Map<Object, Object> map = resources.get();
if (map == null) {
return null;
}
Object value = map.remove(actualKey);
// Remove entire ThreadLocal if empty...
if (map.isEmpty()) {
resources.remove();
}
// Transparently suppress a ResourceHolder that was marked as void...
if (value instanceof ResourceHolder && ((ResourceHolder) value).isVoid()) {
value = null;
}
return value;
}
}
</code></pre>
<p>在上面源码中,每个线程里面的本地变量是一个map,map是以DateSource为key,ConnectionHolder为value。在一个系统可以有多个DataSource,connection又是由相应的DataSource得到的。所以ThreadLocal维护的是以DataSource作为key, 以ConnectionHolder为value的一个Map</p>
<p><img src="https://img2023.cnblogs.com/blog/2358057/202505/2358057-20250512170623779-594683629.png" alt="" loading="lazy"></p>
<p>总结一下,在开启事务的时候,<strong>绑定资源</strong>,<strong>Spring 事务管理器</strong>(如 <code>DataSourceTransactionManager</code>)会调用 <code>doBegin()</code>,获取数据库连接并绑定到 <code>ThreadLocal</code>。</p>
<p>在执行sql的时候,MyBatis 通过 <code>SpringManagedTransaction</code> 获取当前事务的连接</p>
<pre><code class="language-java">// SqlSessionUtils.java
public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType,
PersistenceExceptionTranslator exceptionTranslator) {
.....
SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
SqlSession session = sessionHolder(executorType, holder);
if (session != null) {
return session;
}
LOGGER.debug(() -> "Creating a new SqlSession");
session = sessionFactory.openSession(executorType);
registerSessionHolder(sessionFactory, executorType, exceptionTranslator, session);
return session;
}
// TransactionSynchronizationManager.java
@Nullable
public static Object getResource(Object key) {
Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);
return doGetResource(actualKey);
}
</code></pre>
<p>最后提交事务,相关清理工作.... 就是remove那些了。</p>
<p>总流程如下所示:</p>
<pre><code class="language-java">// TransactionAspectSupport.java
@Nullable
protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targetClass,
final InvocationCallback invocation) throws Throwable {
if (txAttr == null || !(ptm instanceof CallbackPreferringPlatformTransactionManager)) {
// 1.绑定连接的ThreadLocal
TransactionInfo txInfo = createTransactionIfNecessary(ptm, txAttr, joinpointIdentification);
Object retVal;
try {
// 2.进去往下一步执行-- 执行sql【jdbcTempalte、sqlsessionTemplate....】
retVal = invocation.proceedWithInvocation();
}
catch (Throwable ex) {
// 异常回滚
completeTransactionAfterThrowing(txInfo, ex);
throw ex;
}
finally {
// 3.清理工作
cleanupTransactionInfo(txInfo);
}
if (retVal != null && vavrPresent && VavrDelegate.isVavrTry(retVal)) {
// Set rollback-only in case of Vavr failure matching our rollback rules...
TransactionStatus status = txInfo.getTransactionStatus();
if (status != null && txAttr != null) {
retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status);
}
}
commitTransactionAfterReturning(txInfo);
return retVal;
}
}
</code></pre>
<h2 id="end参考">end.参考</h2>
<p>留一个问题:ThreadLocal还有一个很经典的问题,那就是在父子线程中通信的问题了。</p>
<p>1.https://blog.csdn.net/qq_35190492/article/details/107599875</p>
<p>2.https://blog.csdn.net/u010445301/article/details/111322569</p>
<p>3.https://zhuanlan.zhihu.com/p/102571059</p>
<p>4.https://cloud.tencent.com/developer/article/2355282</p><br><br>
来源:https://www.cnblogs.com/jackjavacpp/p/18872943
頁:
[1]