threadLocal如何支持线程池获取

问题:

ThreadLocal默认不支持子线程获取,而InheritableThreadLocal支持子线程获取threadLocal值,但是如果使用线程池,核心个数为1则子线程会获取到上一个threadLocal的值。

解决:

1.引入transmittable-thread-local jar


   com.alibaba
   transmittable-thread-local
   2.11.4

2. threadLocal 初始化

    private static final TransmittableThreadLocal CURRENT_USER_HOLDER = new TransmittableThreadLocal();

3. Executor bean,使用TtlExecutor

@Bean(value = "defaultThreadPool")
    public Executor buildQueueThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        int cpuNum = Runtime.getRuntime().availableProcessors();
        // 设置核心线程数
        executor.setCorePoolSize(Math.min(cpuNum * 2, 16));
        // 设置最大线程数
        executor.setMaxPoolSize(cpuNum * 2);
        //队列中最大的数目
        executor.setQueueCapacity(300);
        //线程名称前缀
        executor.setThreadNamePrefix("defaultThreadPool_");
        //rejection-policy:当pool已经达到max size的时候,如何处理新任务
        //CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
        //对拒绝task的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //线程空闲后的最大存活时间
        executor.setKeepAliveSeconds(60);
        //加载
        executor.initialize();
        return TtlExecutors.getTtlExecutor(executor);
    }

你可能感兴趣的:(java,jvm,开发语言)