ThreadLocal遇上线程池存在的问题

总结:请使用TransmittableThreadLocal使用下文的方法

ThreadLocal是以线程为key的,而线程池里面的线程是会被重新利用的,会导致ThreadLocal出现意料之外的事件。

比如可能会导致在SAAS中的串库。

解决办法如下:

@Slf4j
public class HiThreadPoolExecutor extends ThreadPoolExecutor {
    private Map<Integer, Thread> parentThreadMap = Collections.synchronizedMap(new LinkedHashMap<>());

    public HiThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
                                BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    public HiThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
                                BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
    }

    public HiThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
                                BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
    }

    public HiThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
                                BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
                                RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    }

    @Override
    public void execute(Runnable command) {
        Thread parent = Thread.currentThread();
        // 调用execute方法时,保存当前线程的副本
        parentThreadMap.put(command.hashCode(), new Thread(parent));
        super.execute(command);
    }

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        super.beforeExecute(t, r);
        try {
            Field inheritableThreadLocals = Thread.class.getDeclaredField("inheritableThreadLocals");
            inheritableThreadLocals.setAccessible(true);

            // 取出execute方法中保存的对应父线程副本,并将该副本的inheritableThreadLocals(ThreadLocal变量存放地)设置到即将执行的线程中
            Object value = inheritableThreadLocals.get(parentThreadMap.remove(r.hashCode()));
            if (value != null) inheritableThreadLocals.set(t, value);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            log.error("线程池错误" + HiThreadPoolExecutor.class.getName(), e);
        }
    }
}

原理是利用反射,在线程池提交任务时,将当前环境下的inheritableThreadLocals保存,并在执行线程任务时,提取inheritableThreadLocals并设置到子线程中。

需要注意的是execute方法是在submit时调用的, 而beforeExecute方法是在执行线程任务之前调用的。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值