ThreadLocal (三):为何TransmittableThreadLocal
一、示例
线程池内的线程并没有父子关系,所以不适合InheritableThreadLocal的使用场景
public class ThreadPoolInheritableThreadLocalDemo {
// static ThreadLocal<String> threadLocal = new InheritableThreadLocal<>();
// static ExecutorService pool = Executors.newFixedThreadPool(2);
static TransmittableThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();
static ExecutorService pool = TtlExecutors.getTtlExecutorService(Executors.newFixedThreadPool(3));
public static void main(String[] args) {
for(int i=0;i<100;i++) {
int j = i;
pool.execute(new Thread(new Runnable() {
@Override
public void run() {
ThreadPoolInheritableThreadLocalDemo.threadLocal.set("superWorld"+j);
ThreadPoolInheritableThreadLocalDemo.pool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() +
" : " +
ThreadPoolInheritableThreadLocalDemo.threadLocal.get());
}
});
}
}));
}
}
}
二、TransmittableThreadLocal实现分析

读取线程间传递的ThreadLocal 值比较麻烦,ThreadLocal 和 InheritableThreadLocal 都没有开放内部的 ThreadLocalMap,不能直接读取。
所以要么自己完全实现一套 ThreadLocalMap 机制(如 Netty 的 FastThreadLocal),要么就是自己实现 ThreadLocal 的子类,在每次调用 ThreadLocal
的 set/get/remove 等接口的时候,为 Thread 记录到底绑定了哪些需要发生线程间传递的 ThreadLocal 对象。
/**
*实际存储值的工作还是父类ThreadLocal完成
*TransmittableThreadLocal 只是记录了哪些线程使用了TransmittableThreadLocal对象
*/
@Override
public final void set(T value) {
super.set(value);
if (null == value) { // may set null to remove value
removeValue();
} else {
addValue();
}
}/**
*holder 只是为了记录使用了哪些 TransmittableThreadLocal 对象
*在构造TtlRunnable/TtlCallable 的时候, 通过holder取得对应的TransmittableThreadLocal
*InheritableThreadLocal的默认值是WeakHashMap
*/
private static InheritableThreadLocal<Map<TransmittableThreadLocal<?>, ?>> holder =
new InheritableThreadLocal<Map<TransmittableThreadLocal<?>, ?>>() {
@Override
protected Map<TransmittableThreadLocal<?>, ?> initialValue() {
return new WeakHashMap<TransmittableThreadLocal<?>, Object>();
} @Override
protected Map<TransmittableThreadLocal<?>, ?> childValue(Map<TransmittableThreadLocal<?>, ?> parentValue) {
return new WeakHashMap<TransmittableThreadLocal<?>, Object>(parentValue);
}
}; private void addValue() {
if (!holder.get().containsKey(this)) {
holder.get().put(this, null); // WeakHashMap supports null value.
}
} private void removeValue() {
holder.get().remove(this);
}
调用ThreadPoolInheritableThreadLocalDemo.threadLocal.set("superWorld"+j)时,
holder.get().containskey(this) 为false

2. TtlRunnable
构造TtlRunable时,设置线程对应的Map<TransmittableThreadLocal<?>, Object>>
private TtlRunnable(Runnable runnable, boolean releaseTtlValueReferenceAfterRun) {
//
this.copiedRef = new AtomicReference<Map<TransmittableThreadLocal<?>, Object>>(TransmittableThreadLocal.copy());
this.runnable = runnable;
this.releaseTtlValueReferenceAfterRun = releaseTtlValueReferenceAfterRun;
}
TransmittableThreadLocal.copy
static Map<TransmittableThreadLocal<?>, Object> copy() {
Map<TransmittableThreadLocal<?>, Object> copy = new HashMap<TransmittableThreadLocal<?>, Object>();
for (TransmittableThreadLocal<?> threadLocal : holder.get().keySet()) {
copy.put(threadLocal, threadLocal.copyValue());
}
return copy;
}

3.运行时,备份和恢复Map<TransmittableThreadLocal<?>, Object>
TtlRunnable#run
@Override
public void run() {
Map<TransmittableThreadLocal<?>, Object> copied = copiedRef.get();
if (copied == null || releaseTtlValueReferenceAfterRun && !copiedRef.compareAndSet(copied, null)) {
throw new IllegalStateException("TTL value reference is released after run!");
} Map<TransmittableThreadLocal<?>, Object> backup = TransmittableThreadLocal.backupAndSetToCopied(copied);
try {
runnable.run();
} finally {
TransmittableThreadLocal.restoreBackup(backup);
}
}

参考:
ThreadLocal (三):为何TransmittableThreadLocal的更多相关文章
- ThreadLocal系列(三)-TransmittableThreadLocal的使用及原理解析
ThreadLocal系列(三)-TransmittableThreadLocal的使用及原理解析 上一篇:ThreadLocal系列(二)-InheritableThreadLocal的使用及原理解 ...
- ThreadLocal的进化——TransmittableThreadLocal
上一篇文章中,我们谈到了 InheritableThreadLocal,它解决了 ThreadLocal 针对父子线程无法共享上下文的问题.但我们可能听说过阿里的开源产品TransmittableTh ...
- ThreadLocal系列(二)-InheritableThreadLocal的使用及原理解析
ThreadLocal系列之InheritableThreadLocal的使用及原理解析(源码基于java8) 上一篇:ThreadLocal系列(一)-ThreadLocal的使用及原理解析 下一篇 ...
- ThreadLocal的几种误区
最近由于需要用到ThreadLocal,在网上搜索了一些相关资料,发现对ThreadLocal经常会有下面几种误解 一.ThreadLocal是java线程的一个实现 ThreadLoca ...
- 【原理】Java的ThreadLocal实现原理浅读
当前线程的值传递,ThreadLocal 通过ThreadLocal设值,在线程内可获取,即时获取值时在其它Class或其它Method. public class BasicUsage { priv ...
- ThreadLocal的使用场景分析
目录 一.ThreadLocal介绍 二.使用场景1——数据库事务问题 2.1 问题背景 2.2 方案1-修改接口传参 2.3 方案2-使用ThreadLocal 三.使用场景2——日志追踪问题 四. ...
- 多线程程序设计学习(12)Thread-soecific storage pattern
Thread-Specific-Storage[线程保管箱] 一:Thread-Specific Storage的参与者--->记录日志的线程(ClientThread)--->负责获取不 ...
- 多线程学习三:Thread API,ThreadLocal,synchronized,volatile和Condition
一.Thread API: setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) 首先要了解什么是Thread. ...
- 使用 transmittable-thread-local 组件解决 ThreadLocal 父子线程数据传递问题
在某个项目中,需要使用mybatis-plus多租户功能以便数据隔离,前端将租户id传到后端,后端通过拦截器将该租户id设置到ThreadLocal以便后续使用,代码大体上如下所示: ThreadLo ...
随机推荐
- 从第三方Launcher授权启动指定APP的设计与实现
Case 背景: Case要求从第三方Launcher中首次启动指定的应用程序时.弹出对话框提示用户进行授权启动,若用户未授权,则在下次再次启动该应用时依旧弹出对话框提示用户进行授权.直到用户相应用进 ...
- SDRAM驱动篇之简易SDRAM控制器的verilog代码实现
在Kevin写的上一篇博文<SDRAM理论篇之基础知识及操作时序>中,已经把SDRAM工作的基本原理和SDRAM初始化.读.写及自动刷新操作的时序讲清楚了,在这一片博文中,Kevin来根据 ...
- [ci]gitlab安装配置(含gitlab邮件配置)
gitlab安装配置 参考: https://www.unixhot.com/article/48 原则:简单维护为准,故yum安装gitlab 1,gitlab安装 2,gitlab邮箱配置 1,g ...
- C++语言基础(10)-虚继承
一.产生背景 先看下列一份代码: //间接基类A class A{ protected: int m_a; }; //直接基类B class B: public A{ protected: int m ...
- 92. Reverse Linked List II【Medium】
92. Reverse Linked List II[Medium] Reverse a linked list from position m to n. Do it in-place and in ...
- 李洪强经典面试题53-Swift
李洪强经典面试题53-Swift Swift 网上有很多Swift的语法题,但是Swift现在语法还未稳定,所以在这里暂时不贴出语法题,可以自行搜索. Swift和Objective-C的联系 Swi ...
- 自定义注解日志功能与shrio框架冲突的问题
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w ...
- FreeBSD编译安装emacs,不要用ports
1. 解压emacs 2. 进入解压之后的目录,执行configure命令,大体配置如下: ./configure --with-x-toolkit=no --with-xpm=no --with-j ...
- 华为HiAI 助力苏宁易购,让你尽享完美视觉购物体验!
还在感慨商品照片与实物存在差距,又要退货? 还在抱怨被忽视的图片小细节,影响了生活品质? 想要“买买买”, 又担心海量的商品图片耗光你的流量? 就在近期 搭载HiAI能力的苏宁易购新版上线, 让你畅快 ...
- LeetCode459. Repeated Substring Pattern
Description Given a non-empty string check if it can be constructed by taking a substring of it and ...