ThreadLocal使用不当引发的问题

关于ThreadLocal

我们知道ThreadLocal是为了解决多线程并发访问共享变量时造成数据异常的问题,与加锁的思想方式不同,ThreadLocal是通过为每个线程提供一个变量的副本,以此保证并发访问的安全,其主要适用于在线程中对变量进行隔离。

关于ThreadLocal使用时的问题,除了面试常问的内存泄漏之外,本篇问中有详细说明ThreadLocal存储结构及内存溢出问题分析,本文再来分析另一种问题场景。

案例演示

下面这段代码,定义了一个核心线程数为4的线程池,然后通过一段循环代码来调用线程执行,方法中主要就是先从threadLocal中取出当前数值,然后重新赋一个新值,最后打印下赋值前后的值。

public class Main {

    private static final ExecutorService executorService =
            new ThreadPoolExecutor(4, 4, 0, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<>(100), new MainTreadFactory());

    static class MainTreadFactory implements ThreadFactory {

        private final AtomicInteger threadNum = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "main-thread-" + threadNum .getAndIncrement());
        }
    }

    private static final ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            executorService.execute(Main::m);
        }
    }

    public static void m() {
        String before = Thread.currentThread().getName() + ":" + threadLocal.get();
		threadLocal.set(1);
		String after = Thread.currentThread().getName() + ":" + threadLocal.get();
		System.out.println("before->" + before + "   after->" + after);
    }

}

输出结果如下,正常来说,每一个线程在before时拿到的threadLocal值应该都是0,然后实际情况是只有4个线程拿到的是0,后面都是1

before->main-thread-3:0   after->main-thread-3:1
before->main-thread-2:0   after->main-thread-2:1
before->main-thread-1:0   after->main-thread-1:1
before->main-thread-4:0   after->main-thread-4:1
before->main-thread-1:1   after->main-thread-1:1
before->main-thread-2:1   after->main-thread-2:1
before->main-thread-3:1   after->main-thread-3:1
before->main-thread-2:1   after->main-thread-2:1
before->main-thread-1:1   after->main-thread-1:1
before->main-thread-4:1   after->main-thread-4:1

之所以产生这个问题的原因就是因为使用了线程池,大家都知道线程池中的线程是会被重用的,如果是正常的一段业务逻辑,那也就是说后面几次拿到的都是前面业务中使用过的值。

解决方式

解决方式也很简单,就是一直强调的,threadLocal使用完之后一定要显示的清除。

public static void m() {
    try {
        String before = Thread.currentThread().getName() + ":" + threadLocal.get();
        threadLocal.set(1);
        String after = Thread.currentThread().getName() + ":" + threadLocal.get();
        System.out.println("before->" + before + "   after->" + after);
    } finally {
        threadLocal.remove();
    }
}

再看打印结果就正确了。

before->main-thread-1:0   after->main-thread-1:1
before->main-thread-2:0   after->main-thread-2:1
before->main-thread-4:0   after->main-thread-4:1
before->main-thread-3:0   after->main-thread-3:1
before->main-thread-2:0   after->main-thread-2:1
before->main-thread-1:0   after->main-thread-1:1
before->main-thread-2:0   after->main-thread-2:1
before->main-thread-3:0   after->main-thread-3:1
before->main-thread-4:0   after->main-thread-4:1
before->main-thread-1:0   after->main-thread-1:1

总结

最后要注意的是,此场景不一定是在显示的使用线程池时才会产生,在实际开发中使用的web服务器,比如我们最熟悉的tomcat,本身就是在使用线程池来处理请求,所以之前业务中使用过的线程肯定是会被重用的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

码拉松

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

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

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

打赏作者

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

抵扣说明:

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

余额充值