關(guān)于阿里巴巴TransmittableThreadLocal使用解讀
前言
ThreadLocal在上下文的數(shù)據(jù)傳輸上非常的方便和簡(jiǎn)潔。
工業(yè)實(shí)踐中,比較常用的有三個(gè),ThreadLocal、InheritableThreadLocal、TransmittableThreadLocal,那么他們?nèi)齻€(gè)之間有什么區(qū)別呢?
常見(jiàn)的三種ThreadLocal比較
| ThreadLocal | InheritableThreadLocal | TransmittableThreadLocal | |
| 來(lái)源 | jdk | jdk | 阿里開源 |
| 單線程數(shù)據(jù)傳輸 | 支持 | 支持 | 支持 |
| new線程數(shù)據(jù)傳輸 | 不支持 | 支持 | 支持 |
| 線程池?cái)?shù)據(jù)傳輸 | 不支持 | 部分支持【簡(jiǎn)單場(chǎng)景】 | 支持 |
針對(duì)線程池的數(shù)據(jù)傳輸,InheritableThreadLocal僅僅能在一些簡(jiǎn)單場(chǎng)景下做到,下面就用一個(gè)案例來(lái)說(shuō)明
- 先看下線程工廠的定義
package com.tml.mouseDemo.core.threadLocalDemo;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
public class SimpleThreadFactory implements ThreadFactory {
private static AtomicInteger atomicInteger = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("tml-"+atomicInteger.getAndIncrement());
return t;
}
}- InheritableThreadLocal部分支持的案例
package com.tml.mouseDemo.core.threadLocalDemo;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadLocalDemo1 {
private static ThreadLocal<String> threadLocal = new InheritableThreadLocal<>();
private static ExecutorService service = Executors.newFixedThreadPool(2, new SimpleThreadFactory());
public static void main(String[] args) throws InterruptedException {
threadLocal.set("hello main");
for (int i = 0; i < 2; i++) {
service.execute(() -> {
String s = threadLocal.get();
ThreadUtils.printLog("get data " + s);
});
}
//修改threadLocal中的值
threadLocal.set("hello world");
Thread.sleep(2000);
for (int i = 0; i < 2; i++) {
service.execute(() -> {
String s = threadLocal.get();
ThreadUtils.printLog("get data " + s);
});
}
ThreadUtils.printLog("get data " + threadLocal.get());
service.shutdown();
}
}- 運(yùn)行結(jié)果如下
2025-01-10 19:41:50 | INFO | tml-1 | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello main
2025-01-10 19:41:50 | INFO | tml-2 | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello main
2025-01-10 19:41:52 | INFO | tml-2 | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello main
2025-01-10 19:41:52 | INFO | main | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello world
2025-01-10 19:41:52 | INFO | tml-1 | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello main
從運(yùn)行結(jié)果來(lái)看,前面的兩次循環(huán)提交的任務(wù),在子線程中確實(shí)是能正常的獲取主線程設(shè)置的變量,即hello main,但是緊接著,我修改了主線程上綁定的變量為hello world,然后繼續(xù)循環(huán)兩次提交兩個(gè)任務(wù),這個(gè)時(shí)候子線程中獲取的線程變量依然是hello main,這明顯是與是期望不一致的。
從這個(gè)層面來(lái)講,InheritableThreadLocal確實(shí)在線程池的層面支持不夠友好,可以說(shuō)僅支持部分簡(jiǎn)單場(chǎng)景。
根本原因就死線程池的池化機(jī)制,從上面的運(yùn)行日志上也可以看出,提交了4個(gè)任務(wù)執(zhí)行的線程依然是兩個(gè)。線程池中的線程是復(fù)用的,InheritableThreadLocal是在創(chuàng)建子線程的時(shí)候,會(huì)將主線程上綁定的數(shù)據(jù)拷貝過(guò)來(lái),如果我不創(chuàng)建新的線程,但是主線程上綁定的數(shù)據(jù)改變了呢?那我依然還是讀取到之前拷貝的數(shù)據(jù)。
這個(gè)就是InheritableThreadLocal的短板。針對(duì)這個(gè)問(wèn)題,阿里開源的TransmittableThreadLocal就能順利絲滑的解決這個(gè)問(wèn)題。
TransmittableThreadLocal實(shí)踐
maven依賴
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>transmittable-thread-local</artifactId>
<version>2.12.4</version>
</dependency>裝飾Runnable任務(wù)
- 直接看代碼
package com.tml.mouseDemo.core.threadLocalDemo;
import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.TtlRunnable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadLocalDemo1 {
private static ThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();
private static ExecutorService service = Executors.newFixedThreadPool(2, new SimpleThreadFactory());
public static void main(String[] args) throws InterruptedException {
threadLocal.set("hello main");
for (int i = 0; i < 2; i++) {
service.execute(TtlRunnable.get(() -> {
String s = threadLocal.get();
ThreadUtils.printLog("get data " + s);
}));
}
//修改threadLocal中的值
threadLocal.set("hello world");
Thread.sleep(2000);
for (int i = 0; i < 2; i++) {
service.execute(TtlRunnable.get(() -> {
String s = threadLocal.get();
ThreadUtils.printLog("get data " + s);
}));
}
ThreadUtils.printLog("get data " + threadLocal.get());
service.shutdown();
}
}- 運(yùn)行結(jié)果如下:
2025-01-10 19:57:03 | INFO | tml-2 | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello main
2025-01-10 19:57:03 | INFO | tml-1 | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello main
2025-01-10 19:57:05 | INFO | tml-1 | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello world
2025-01-10 19:57:05 | INFO | main | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello world
2025-01-10 19:57:05 | INFO | tml-2 | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello world
與第一個(gè)案例的差異點(diǎn)在于,使用了
public static TtlRunnable get(@Nullable Runnable runnable) {
return get(runnable, false, false);
}來(lái)增強(qiáng)了了Runnable任務(wù),執(zhí)行的結(jié)果也是符合預(yù)期。
裝飾線程池
- 直接看代碼
package com.tml.mouseDemo.core.threadLocalDemo;
import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.TtlRunnable;
import com.alibaba.ttl.threadpool.TtlExecutors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadLocalDemo1 {
private static ThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();
private static ExecutorService service = Executors.newFixedThreadPool(2, new SimpleThreadFactory());
private static ExecutorService ttlExecutorService = TtlExecutors.getTtlExecutorService(service);
public static void main(String[] args) throws InterruptedException {
threadLocal.set("hello main");
for (int i = 0; i < 2; i++) {
ttlExecutorService.execute(() -> {
String s = threadLocal.get();
ThreadUtils.printLog("get data " + s);
});
}
//修改threadLocal中的值
threadLocal.set("hello world");
Thread.sleep(2000);
for (int i = 0; i < 2; i++) {
ttlExecutorService.execute(() -> {
String s = threadLocal.get();
ThreadUtils.printLog("get data " + s);
});
}
ThreadUtils.printLog("get data " + threadLocal.get());
service.shutdown();
}
}- 運(yùn)行結(jié)果如下
2025-01-10 20:05:05 | INFO | tml-2 | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello main
2025-01-10 20:05:05 | INFO | tml-1 | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello main
2025-01-10 20:05:07 | INFO | tml-2 | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello world
2025-01-10 20:05:07 | INFO | main | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello world
2025-01-10 20:05:07 | INFO | tml-1 | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello world
與上一個(gè)案例的差異點(diǎn)在于,這里沒(méi)有包裝Runnable任務(wù),而是包裝了線程池,使用了
public static ExecutorService getTtlExecutorService(@Nullable ExecutorService executorService) {
if (TtlAgent.isTtlAgentLoaded() || executorService == null || executorService instanceof TtlEnhanced) {
return executorService;
}
return new ExecutorServiceTtlWrapper(executorService, true);
}包裝了ExecutorService,執(zhí)行結(jié)果也是符合預(yù)期
使用java Agent無(wú)侵入增強(qiáng)線程池
- 直接看代碼
package com.tml.mouseDemo.core.threadLocalDemo;
import com.alibaba.ttl.TransmittableThreadLocal;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadLocalDemo1 {
private static ThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();
private static ExecutorService service = Executors.newFixedThreadPool(2, new SimpleThreadFactory());
public static void main(String[] args) throws InterruptedException {
threadLocal.set("hello main");
for (int i = 0; i < 2; i++) {
service.execute(() -> {
String s = threadLocal.get();
ThreadUtils.printLog("get data " + s);
});
}
//修改threadLocal中的值
threadLocal.set("hello world");
Thread.sleep(2000);
for (int i = 0; i < 2; i++) {
service.execute(() -> {
String s = threadLocal.get();
ThreadUtils.printLog("get data " + s);
});
}
ThreadUtils.printLog("get data " + threadLocal.get());
service.shutdown();
}
}項(xiàng)目運(yùn)行的時(shí)候,需要添加額外的jvm啟動(dòng)參數(shù),如下

- 運(yùn)行結(jié)果如下,也是符合預(yù)期
2025-01-10 20:11:59 | INFO | tml-2 | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello main
2025-01-10 20:11:59 | INFO | tml-1 | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello main
2025-01-10 20:12:01 | INFO | tml-2 | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello world
2025-01-10 20:12:01 | INFO | main | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello world
2025-01-10 20:12:01 | INFO | tml-1 | com.tml.mouseDemo.core.threadLocalDemo.ThreadUtils | get data hello world
總結(jié)
阿里巴巴的TransmittableThreadLocal是繼承自InheritableThreadLocal,對(duì)他的功能進(jìn)行了增強(qiáng),增強(qiáng)的點(diǎn)也主要是在線程池的支持上。
通過(guò)上面的三個(gè)案例,可以看到TransmittableThreadLocal是非常靈活的,大家可以根據(jù)自己的需要,選擇對(duì)應(yīng)的方式來(lái)實(shí)現(xiàn)。
TransmittableThreadLocal的官網(wǎng)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java+mysql實(shí)現(xiàn)學(xué)籍管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Java+mysql實(shí)現(xiàn)學(xué)籍管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-07-07
Java連接 JDBC基礎(chǔ)知識(shí)(操作數(shù)據(jù)庫(kù):增刪改查)
這篇文章主要介紹了Java連接 JDBC基礎(chǔ)知識(shí),包括操作數(shù)據(jù)庫(kù)之增刪改查操作,需要的朋友可以參考下2021-04-04
使用Java操作MySQL實(shí)現(xiàn)數(shù)據(jù)交互的方法
JDBC是Java中用于操作數(shù)據(jù)庫(kù)的API,可以為多種關(guān)系數(shù)據(jù)庫(kù)提供統(tǒng)一訪問(wèn),它通過(guò)JDK自帶的JDBC API和數(shù)據(jù)庫(kù)驅(qū)動(dòng)包進(jìn)行操作,實(shí)現(xiàn)數(shù)據(jù)庫(kù)的增刪改查,本文給大家介紹使用Java操作MySQL實(shí)現(xiàn)數(shù)據(jù)交互的方法,感興趣的朋友跟隨小編一起看看吧2025-01-01
SpringBoot如何取消內(nèi)置Tomcat啟動(dòng)并改用外接Tomcat
這篇文章主要介紹了SpringBoot如何取消內(nèi)置Tomcat啟動(dòng)并改用外接Tomcat,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11
深入詳解SpringBoot配置diff的實(shí)戰(zhàn)方法
在日常的開發(fā)與運(yùn)維工作中,配置管理是一項(xiàng)至關(guān)重要的任務(wù),簡(jiǎn)單來(lái)說(shuō),Spring Boot 配置 diff 就是對(duì)比 Spring Boot 應(yīng)用中不同配置版本之間的差異,下面小編就和大家詳細(xì)介紹一下Spring Boot 配置 diff 的實(shí)戰(zhàn)方法吧2026-04-04
高分面試從Hotspot源碼層面剖析java多態(tài)實(shí)現(xiàn)原理
這篇文章主要為大家介紹了在面試中從Hotspot源碼層面來(lái)剖析java多態(tài)的實(shí)現(xiàn)原理,這樣回答薪資隨你開,有需要的朋友可以借鑒參考下,希望大家多多加薪2022-01-01

