【InheritableThreadLocal】搭配线程池使用存在问题

🏆 问题描述

服务中多接口报空指针异常,以报错邮件中的接口参数调用接口时,接口调用正常;
推断接口空指针邮件错发(A接口报空指针,邮件使用的接口信息为B接口信息)


🎯异常定位

能接收到报错邮件,肯定是有空指针异常;报错邮件是根据log4j抓取的异常触发。

接口信息来源

接口信息使用过滤器在接口请求时,将接口信息存放在MDC中。
在这里插入图片描述

MDC (Mapped Diagnostic Context) 可以看成是一个与当前线程绑定的哈希表;
在这里插入图片描述

空指针异常(定位异常点)

报错的接口中都是使用的多线程处理,在几个接口处理异常时都打印具体异常标识,重新发版之后;多接口异常信息都指向同一个处理异常处理点;

在这里插入图片描述


⭐️原因分析

异常处理方式

异步调用,异常处理方法

 List<PropertyStatisticsAvailableDataDto> availableDataDtoList = new ArrayList<>();
        CompletableFuture<Void> availableDataDtoListFuture = CompletableFuture.supplyAsync(() -> {
            return getPropertyStatisticsAvailableDataList(bo);
        }, executor).thenAccept(result -> {
            if (result != null && !result.isEmpty()) {
                availableDataDtoList.addAll(result);
            }
        }).exceptionally(e -> {
            logger.error("可售数据报错" + e.getMessage());
            return null;
        });

可以看到异常处理机制是使用从线程池中拿到的子线程进行异常处理。那就看一下为什么子线程中存放在MDC 中的接口信息为什么有误?

MDC中接口信息(源码调用)

查看调用源码MDC底层使用InheritableThreadLocal存储信息的。如下是源码调用。

  1. org.slf4j.MDC#put使用mdcAdapterput方法
    在这里插入图片描述

  2. mdcAdapter创建使用org.slf4j.MDC#bwCompatibleGetMDCAdapterFromBinder方法。
    在这里插入图片描述

  3. 调用org.slf4j.impl.StaticMDCBinder#getMDCA 创建Log4jMDCAdapter对象在这里插入图片描述

  4. 调用org.apache.logging.slf4j.Log4jMDCAdapter#put在这里插入图片描述

  5. ThreadContext中调用初始化,useStack ,useMap 默认为true在这里插入图片描述

  6. org.apache.logging.log4j.spi.ThreadContextMapFactory#createThreadContextMap,第一次创建createDefaultThreadContextMap方法
    在这里插入图片描述

  7. org.apache.logging.log4j.spi.ThreadContextMapFactory#createDefaultThreadContextMap在这里插入图片描述
    8.三个底层方法都使用了InheritableThreadLocal类;org.apache.logging.log4j.spi.CopyOnWriteSortedArrayThreadContextMap#CopyOnWriteSortedArrayThreadContextMap在这里插入图片描述

InheritableThreadLocal源码分析

查看InheritableThreadLocal源码,线程init方法中将父线程变量存储到子线程中。如下是源码调用。

  • InheritableThreadLocal用来传递父线程生成的变量到子线程中进行使用,继承了 ThreadLocal类;
    在这里插入图片描述
  • Thread类中维护了ThreadLocal,InheritableThreadLocal,数据类型都是ThreadLocalMap(线程私有);
    在这里插入图片描述
  • java.lang.Thread#init(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long)初始化对InheritableThreadLocal进行处理在这里插入图片描述

⭐️猜想验证

接口信息是存储到InheritableThreadLocal中的,在线程初始化的时候,会将父线程的变量值赋值给子线程;业务中使用线程池调用子线程,如果子线程并不是新创建的,而是已经创建过的线程,这样就不会更新接口信息(接口信息先存储主线程中);
在这里插入图片描述


✨模拟错误

  • 创建线程池将核心线程数设置为

在这里插入图片描述

  • 模拟示例
 private static InheritableThreadLocal inheritableThreadLocal=    new InheritableThreadLocal<>();

    @Override
    public void TestOne() {

        ArrayList<String> supplyDataDtoList = new ArrayList<>();
        //模拟写入接口信息
        inheritableThreadLocal.set("TestOne");
        CompletableFuture.supplyAsync(() -> {
            return getPropertyStatisticsSupplyDataList1();
        },executor).thenAccept(result -> {
            if (result != null && !result.isEmpty()) {
                supplyDataDtoList.addAll(result);
            }
        }).exceptionally(e -> {
            logger.error("TestOne" + e.getMessage());
            return null;
        });


    }

    @Override
    public void TestTwo() {
        //模拟写入接口信息
        inheritableThreadLocal.set("TestTwo");
        ArrayList<String> supplyDataDtoList = new ArrayList<>();
        CompletableFuture.supplyAsync(() -> {
            return getPropertyStatisticsSupplyDataList();
        },executor).thenAccept(result -> {
            if (result != null && !result.isEmpty()) {
                supplyDataDtoList.addAll(result);
            }
        }).exceptionally(e -> {
            logger.error("TestTwo" + e.getMessage());
            return null;
        });
    }


    //异步方法A
    private  List<String> getPropertyStatisticsSupplyDataList1(){
        ArrayList<String> supplyDataDtoList = new ArrayList<>();
        //打印inheritableThreadLocal变量
        System.out.println("打印异步方法AinheritableThreadLocal变量->"+Thread.currentThread().getName()+inheritableThreadLocal.get());
        return supplyDataDtoList;
    }

    //异步方法B
    private  List<String> getPropertyStatisticsSupplyDataList(){
        ArrayList<String> supplyDataDtoList = new ArrayList<>();
        String name=null;
        //打印inheritableThreadLocal变量
        System.out.println("打印异步方法BinheritableThreadLocal变量->"+Thread.currentThread().getName()+inheritableThreadLocal.get());
        System.out.println(name.toString());

        return supplyDataDtoList;
    }
  • 先请求A接口,然后多次并发请求B接口。控制台打印在这里插入图片描述
  • 先多次并发请求B接口,然后请求A接口。控制台打印在这里插入图片描述

🎉结论&解决

Log4j记录日志MDC使用InheritableThreadLocal,而搭配线程池使用时,高并发情况下子线程InheritableThreadLocal容易出现不更新父线程变量的情况。

  • 对于使用线程池异步处理处理数据,使用主线程进行异常处理;(业务使用这种方式,在不改log4j源码包的情况下,使用这种方式,正确抓取异常)
CompletableFuture<List<PropertyStatisticsAvailableDataDto>> availableDataDtoListFuture = CompletableFuture.supplyAsync(() -> {
            return getPropertyStatisticsAvailableDataList(bo);
        }, executor);
 CompletableFuture.allOf(availableDataDtoListFuture).join();
        List<PropertyStatisticsAvailableDataDto> propertyStatisticsAvailableDataDtos=null;
        //这里使用主线程处理异常
        try {
            availableDataDtoList = availableDataDtoListFuture.get();
        } catch (Exception e) {
        	
            logger.error("可售数据报错" + getStackTrace(e));
        }
<!-- https://mvnrepository.com/artifact/com.alibaba/log4j2-ttl-thread-context-map -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>log4j2-ttl-thread-context-map</artifactId>
    <version>1.3.3</version>
</dependency>

TransmittableThreadLocal方案

  • 🍪 Maven依赖
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>transmittable-thread-local</artifactId>
			<version>2.2.0</version>
		</dependency>
  • 🍍使用新ThreadLocal
private static TransmittableThreadLocal<String> inheritableThreadLocal=    new TransmittableThreadLocal();
  • 🍋对线程池进行处理(官方提供3种方式,这里使用对线程池进行修饰)
Executor ttlExecutor = TtlExecutors.getTtlExecutor(threadPool);

在这里插入图片描述

  • 先请求A接口,然后多次并发请求B接口。控制台打印;打印结果正常。

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
使用线程池时,可能会遇到InheritableThreadLocal无法正确继承的问题。这是因为线程池在执行任务时会重用之前创建的线程,而这些线程可能已经绑定了旧的InheritableThreadLocal值,导致新任务继承错误的值。解决这个问题的办法是使用ThreadPoolExecutor而不是ThreadPool来创建线程池,并覆盖它的`ThreadFactory`方法,以创建一个新的线程并正确地继承InheritableThreadLocal值。具体来说,可以创建一个实现`ThreadFactory`接口的类,并覆盖`newThread`方法,如下所示: [^2] ```python import threading from concurrent.futures import ThreadPoolExecutor, _base class MyThreadLocal(_base.Executor): def __init__(self, thread_local): self.thread_local = thread_local def submit(self, fn, *args, **kwargs): return super().submit(self.wrapper(fn), *args, **kwargs) def wrapper(self, fn): local = self.thread_local.copy() def wrapped_fn(*args, **kwargs): with local: return fn(*args, **kwargs) return wrapped_fn def map(self, fn, *iterables, timeout=None, chunksize=1): return list(self._map_async(fn, *iterables).result(timeout=timeout)) def shutdown(self, wait=True): pass class MyThreadFactory(ThreadPoolExecutor): def __init__(self, thread_local, *args, **kwargs): self.thread_local = thread_local super().__init__(*args, **kwargs) def new_thread(self, executor, task): t = threading.Thread(target=executor._worker, args=(task,), daemon=True) t.daemon = False t.name = None t._Thread__ident = None t._target = None t._args = None t._kwargs = None t._state = threading.S t._thread_local = self.thread_local return t # 使用示例: import random import time def test_inheritable_thread_local(thread_local, pool): thread_local.value = random.randint(0, 100) pool.submit(worker, thread_local.copy()) def worker(thread_local_copy): print(thread_local_copy.value) time.sleep(1) print(thread_local_copy.value) if __name__ == '__main__': thread_local = threading.local() pool = MyThreadLocal(thread_local) factory = MyThreadFactory(thread_local, 5) pool._threads = set() pool._max_workers = 5 pool._thread_name_prefix = 'ThreadPoolExecutor-' pool._initializer = None pool._initargs = () pool._queue = queue.Queue() pool._task_counter = itertools.count() pool._shutdown = False pool._results = {} pool._work_ids = set() pool._threads_lock = threading.Lock() pool._threads_recreate_lock = threading.Lock() pool._pending_work_items_lock = threading.Lock() pool._wake_up_mutex = threading.Lock() pool._not_responsive_workers = set() pool._shutdown_thread = None pool._shutdown_lock = threading.Lock() pool._shutdown_cond = threading.Condition(pool._shutdown_lock) pool._workers = {} pool._done_with_recreate = threading.Condition() pool._threads_recreate_override = False pool._threads_recreate_count = 0 pool._threads_recreate_next_id = 0 pool._threads_recreate_idle_time = 0.0 pool._threads_recreate_rate = 0.5 pool._threads_recreate_max = 5 pool._threads_recreate_last = 0.0 pool._threads_recreate_reset = False pool._kill_workers = False pool._force_workers = set() pool._shutdown_lock = threading.Lock() pool._shutdown_cond = threading.Condition(pool._shutdown_lock) pool._stop_f = None pool._threads_recreate_condition = threading.Condition(pool._threads_recreate_lock) pool._thread_factory = factory test_inheritable_thread_local(thread_local, pool) pool.shutdown() ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Abner G

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值