如何将ThreadLocal传递到子线程

在项目开发的过程中,我们常常会把一些常用的线程上下文信息放到ThreadLocal中(如Spring中的RequestContextHolder),方便在程序中随时调取。但是在使用多线程时父线程中的ThreadLocal通常无法直接传递到子线程中去,容易造成程序bug。
这种情况通常有两种方式将父线程中的ThreadLocal传递到子线程中。
方法一:
最常规的想法是在编写子线程任务时,每次都手动的将子线程需要用到的ThreadLocal数据传递到子线程中,这样子线程也能过随时获取到线程上下文信息。

方法二:
自定义一个ThreadPoolExecutor代替系统的ThreadPoolExecutor,每次用线程池提交线程任务时,线程池会自动将父线程的ThreadLocal自动传递到子线程中,避免每次手动传递ThreadLocal到子线程。

代码如下所示:

public class TraceThreadPoolExecutor extends ThreadPoolExecutor {

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

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

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

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

    /**
     * 覆盖execute方法,将一些上下文信息传递到子线程,如登陆用户信息等
     */
    @Override
    public void execute(final Runnable command) {
        final LoginUser loginUser = getLoginUser();
        Runnable task = new Runnable() {
            @Override
            public void run() {
                SessionInfoContextHolder.setLoginInfo(loginUser);
                try{
                    command.run();
                } catch (Exception e){
                //dosomething
                } finally {
                    clearLoginInfo();
                }
            }
        };
        super.execute(task);
    }

}

个人博客文章地址:http://dushenzhi.top/2016/12/11/%E5%B0%86ThreadLocal%E4%BC%A0%E9%80%92%E5%88%B0%E5%AD%90%E7%BA%BF%E7%A8%8B/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值