曹耘豪的博客

Alibaba的TransmittableThreadLocal

  1. TransmittableThreadLocal特性
  2. 案例对比
    1. new Thread() + InheritableThreadLocal,可取到
    2. 线程池 + InheritableThreadLocal,不可取到
    3. new Thread() + TransmittableThreadLocal,和InheritableThreadLocal一致
    4. 原生线程池 + TransmittableThreadLocal,不可取到
    5. TTL包装器线程池 + TransmittableThreadLocal,可取到
  3. 大致原理
    1. 核心方法解释
  4. 其他特性

TransmittableThreadLocal特性

案例对比

new Thread() + InheritableThreadLocal,可取到

1
2
3
4
5
InheritableThreadLocal<String> threadLocal = new InheritableThreadLocal<>();
threadLocal.set("a");

new Thread(() -> {System.out.println(threadLocal.get());}).start();
// 输出a

线程池 + InheritableThreadLocal,不可取到

1
2
3
4
5
6
7
8
9
ExecutorService executor = Executors.newFixedThreadPool(1);
// 先初始化进程,确保线程初始化时上下文中没有ThreadLocal信息
executor.submit(() -> {System.out.println("init");}).get();

InheritableThreadLocal<String> threadLocal = new InheritableThreadLocal<>();
threadLocal.set("a");

executor.execute(() -> {System.out.println(threadLocal.get());});
// 输出null

new Thread() + TransmittableThreadLocal,和InheritableThreadLocal一致

1
2
3
4
5
TransmittableThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();
threadLocal.set("a");

new Thread(() -> {System.out.println(threadLocal.get());}).start();
// 输出a

原生线程池 + TransmittableThreadLocal,不可取到

1
2
3
4
5
6
7
8
9
10
11
12
ExecutorService executor = Executors.newFixedThreadPool(1);
// 先初始化进程,确保线程初始化时上下文中没有ThreadLocal信息
executor.submit(() -> {System.out.println("init");}).get();

TransmittableThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();
threadLocal.set("a");

executor.execute(() -> {System.out.println(threadLocal.get());});

// 输出
// init
// null

TTL包装器线程池 + TransmittableThreadLocal,可取到

1
2
3
4
5
6
7
8
9
10
11
12
ExecutorService executor = TtlExecutors.getTtlExecutorService(Executors.newFixedThreadPool(1));
// 先初始化进程,确保线程初始化时上下文中没有ThreadLocal信息
executor.submit(() -> {System.out.println("init");}).get();

TransmittableThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();
threadLocal.set("a");

executor.execute(() -> {System.out.println(threadLocal.get());});

// 输出
// init
// a

大致原理

核心方法解释

其他特性

   /