transmittable-thread-local:解決線程池直接ThreadLocal本地變量傳遞的問題

歡迎關注本人公衆號

在這裏插入圖片描述

概述

當InheritableThreadLocal遇到線程池:主線程本地變量修改後,子線程無法讀取到新值 一文中介紹了InheritableThreadLocal的問題:主線程變量修改後,子線程無法取到的問題。

阿里開源的transmittable-thread-local解決了這個問題。

transmittable-thread-local介紹

git地址:transmittable-thread-local

需求場景

在ThreadLocal的需求場景即是TTL的潛在需求場景,如果你的業務需要『在使用線程池等會池化複用線程的執行組件情況下傳遞ThreadLocal』則是TTL目標場景。

下面是幾個典型場景例子。

  • 分佈式跟蹤系統
  • 日誌收集記錄系統上下文
  • Session級Cache
  • 應用容器或上層框架跨應用代碼給下層SDK傳遞信息

實例

public class TransmittableThreadLocalTest1 {
    public static ThreadLocal<Integer> threadLocal = new TransmittableThreadLocal<>();
    public static ExecutorService executorService =
            TtlExecutors.getTtlExecutorService(Executors.newFixedThreadPool(1));

    public static void main(String[] args) throws InterruptedException {
        System.out.println("主線程開啓");
        threadLocal.set(1);

        executorService.submit(() -> {
            System.out.println("子線程讀取本地變量:" + threadLocal.get());
        });

        TimeUnit.SECONDS.sleep(1);

        threadLocal.set(2);

        executorService.submit(() -> {
            System.out.println("子線程讀取本地變量:" + threadLocal.get());
        });
    }
}

運行結果:

主線程開啓
子線程讀取本地變量:1
子線程讀取本地變量:2

可以看到,父線程修改了本地變量後,子線程成功讀取到。

實現原理

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章