ThreadLocal学习

ThreadLocal学习

ThreadLocal实现原理

ThreadLocal.ThreadLocalMap

首先,每个Thread 里面都有一个成员 ThreadLocal.ThreadLocalMap 类型的成员变量

    static class ThreadLocalMap {
        //内部存储其实是一个 entry 的数组结构
        private Entry[] table;
    }
  static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }

看到这里我们应该清楚了 ThreadLocal.ThreadLocalMap 的数据结构,如下图

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YeVbUiSu-1668950584616)(https://weijinhao.gitee.io/markdown-picture/ThreadLocal原理图.png)]

因为ThreadLocal.ThreadLocalMap 类型的变量 是Thread 的成员变量,所以其有线程隔离性.

那么ThreadLocal.ThreadLocalMap中的数据是从什么地方写入或者读取的呢?那时就ThreadLocal这个类所实现的功能了。

ThreadLocal

这里我们着重分析一个 ThreadLocal的 get() 方法set(T value)方法remove()方法

 public T get() {
     //获取当前线程
        Thread t = Thread.currentThread();
     //获取当前线程的threadLocals 成员变量
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            //获取以当前TheadLocal对象为key 的key-value 键值对
            ThreadLocalMap.Entry e = map.getEntry(this);
            
            if (e != null) {
                @SuppressWarnings("unchecked")
                //返回value
                T result = (T)e.value;
                return result;
            }
        }
     //否则调用setInitialValue方法返回默认值
        return setInitialValue();    1
    }
1    
private T setInitialValue() {
        //我们可以重载该方法,初始化默认值
        T value = initialValue();    2
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        
        if (map != null)
            map.set(this, value);
        else
            //创建ThreadLocalMap,并存储到Thread 中
            createMap(t, value);   3
        return value;
    }
//我们可以重载该方法,初始化默认值
2
  protected T initialValue() {
        return null;
    }
//创建
3
void createMap(Thread t, T firstValue) {
    //赋值给当前线程
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

set() 方法类似

   public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

remove()方法

   public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     }

threadLocal 使用风险

最大的风险就是产生的内存泄漏风险,

 static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }

通过构造函数我们知道 key 为弱引用,value 为强引用。

当threadLocal变量被置为null时,Heap中的threadLocal对象失去了引用,将被GC回收。同时Entry的key也将被回收。Entry中只剩下没有key的Value,此时存在强引用链threadlocalmap–>Entry–>Value,若当前线程迟迟不能结束,则Heap中的Value始终不能被GC回收,造成内存泄漏。所以必须建议 最好的办法在不使用ThreadLocal的时候,调用remove()方法,通过显示 的设置value = null 清除数据。

为了避免内存泄漏,ThreadLocalMap在调用get()方法和set()方法时操作数组时,也会去调用expungeStaleEntry()方法来清除Entry中key为null的Value,但是这种清理是不及时,因为我们不保证时候还会触发get()方法和set()等方法。因此也会引发内存泄漏的风险。只有remove()方法,显式调用expungeStaleEntry()方法,才是王道。

使用场景

场景1

线程内保存全局变量,可以让不同方法直接使用,避免参数传递麻烦,例如数据源切换

@Configuration
public class DataSourceProxyConfig {
	//数据源1
    @Bean("originOrder")
    @ConfigurationProperties(prefix = "spring.datasource.order")
    public DataSource dataSourceMaster() {
        return new DruidDataSource();
    }
	//数据源2
    @Bean("originStorage")
    @ConfigurationProperties(prefix = "spring.datasource.storage")
    public DataSource dataSourceStorage() {
        return new DruidDataSource();
    }
	//数据源3
    @Bean("originPay")
    @ConfigurationProperties(prefix = "spring.datasource.pay")
    public DataSource dataSourcePay() {
        return new DruidDataSource();
    }
	//数据源4
    @Bean(name = "order")
    public DataSourceProxy masterDataSourceProxy(@Qualifier("originOrder") DataSource dataSource) {
        return new DataSourceProxy(dataSource);
    }
	//数据源5
    @Bean(name = "storage")
    public DataSourceProxy storageDataSourceProxy(@Qualifier("originStorage") DataSource dataSource) {
        return new DataSourceProxy(dataSource);
    }
	//数据源6
    @Bean(name = "pay")
    public DataSourceProxy payDataSourceProxy(@Qualifier("originPay") DataSource dataSource) {
        return new DataSourceProxy(dataSource);
    }

    @Bean("dynamicDataSource")
    public DataSource dynamicDataSource(@Qualifier("order") DataSource dataSourceOrder,
                                        @Qualifier("storage") DataSource dataSourceStorage,
                                        @Qualifier("pay") DataSource dataSourcePay) {
		//动态数据源,这是spring 为我们提供的
        DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource();

        Map<Object, Object> dataSourceMap = new HashMap<>(3);
        dataSourceMap.put(DataSourceKey.ORDER.name(), dataSourceOrder);
        dataSourceMap.put(DataSourceKey.STORAGE.name(), dataSourceStorage);
        dataSourceMap.put(DataSourceKey.PAY.name(), dataSourcePay);

        dynamicRoutingDataSource.setDefaultTargetDataSource(dataSourceOrder);
        //数据源以键值对的形式存储
        dynamicRoutingDataSource.setTargetDataSources(dataSourceMap);
		
        DynamicDataSourceContextHolder.getDataSourceKeys().addAll(dataSourceMap.keySet());

        return dynamicRoutingDataSource;
    }

    @Bean
    @ConfigurationProperties(prefix = "mybatis")
    public SqlSessionFactoryBean sqlSessionFactoryBean(@Qualifier("dynamicDataSource") DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

}
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        log.info("当前数据源 [{}]", DynamicDataSourceContextHolder.getDataSourceKey());
        //调用我们的ThreadLocal 获取数据源的key
        return DynamicDataSourceContextHolder.getDataSourceKey();
    }
}
public class DynamicDataSourceContextHolder {

    private static final ThreadLocal<String> CONTEXT_HOLDER = ThreadLocal.withInitial(DataSourceKey.ORDER::name);

    private static List<Object> dataSourceKeys = new ArrayList<>();

    public static void setDataSourceKey(DataSourceKey key) {
        CONTEXT_HOLDER.set(key.name());
    }

    public static String getDataSourceKey() {
        return CONTEXT_HOLDER.get();
    }

    public static void clearDataSourceKey() {
        CONTEXT_HOLDER.remove();
    }

    public static List<Object> getDataSourceKeys() {
        return dataSourceKeys;
    }
}

在程序代码中我们就可以使用DynamicDataSourceContextHolder.setDataSourceKey(),进行数据源的切换了。

在业务代码执行完成后,记得显示调用clearDataSourceKey()方法清除数据。

为了方便使用,我们完成一下,就是可以在需要切换数据源ServiceMapper方法上添加@DataSource注解,来实现数据源的切换功能

本实现出自ruoyi项目,感谢若依

声明一个切面,拦截包含 @DataSource注解的方法

@Component
public class DataSourceAspect
{
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(com.ruoyi.common.annotation.DataSource)"
            + "|| @within(com.ruoyi.common.annotation.DataSource)")
    public void dsPointCut()
    {

    }

    @Around("dsPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable
    {
        DataSource dataSource = getDataSource(point);

        if (StringUtils.isNotNull(dataSource))
        {
            DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
        }

        try
        {
            return point.proceed();
        }
        finally
        {
            // 销毁数据源 在执行方法之后
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }

    /**
     * 获取需要切换的数据源
     */
    public DataSource getDataSource(ProceedingJoinPoint point)
    {
        MethodSignature signature = (MethodSignature) point.getSignature();
        DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
        if (Objects.nonNull(dataSource))
        {
            return dataSource;
        }

        return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
    }
}
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface DataSource
{
    /**
     * 切换数据源名称
     */
    public DataSourceType value() default DataSourceType.MASTER;
}

这样就可以在方法上直接使用@DataSource 注解实现数据源的切换功能了。再次强调,一定要显示调用remove 方法确保内存回收。

场景2

每个线程需要一个独享的对象,比如非线程安全的工具类 例如SimpleDateFormt

class SimpleDateFormtHolder {
    private static ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<SimpleDateFormat>() {
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyy-MM-dd");
        }
    };

    public static SimpleDateFormat getSimpleDateFormt() {
        return threadLocal.get();
    }

    public static void setSimpleDateFormt(SimpleDateFormat simpleDateFormat) {
         threadLocal.set(simpleDateFormat);
    }

    public static void removeSimpleDateFormt() {
        threadLocal.remove();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ThreadLocal是一种特殊的变量存储类,它允许每个线程拥有自己的副本变量,从而避免了线程之间的共享变量冲突。在Java中,ThreadLocal通常用于存储线程局部数据,即每个线程都有自己的数据副本,而不会受到其他线程的影响。 要使用ThreadLocal,首先需要创建一个ThreadLocal对象,并使用其set()方法将数据存储在当前线程的副本中。例如: ```java ThreadLocal<Integer> threadLocal = new ThreadLocal<>(); threadLocal.set(42); ``` 在这个例子中,我们创建了一个ThreadLocal对象threadLocal,并将其初始化为空值。然后,我们使用set()方法将整数值42存储在当前线程的副本中。 接下来,我们可以通过get()方法从当前线程中获取存储在该ThreadLocal对象中的值。例如: ```java int value = threadLocal.get(); ``` 这个例子中,我们从当前线程的副本中获取了存储在threadLocal中的值,并将其存储在变量value中。由于每个线程都有自己的副本,因此我们可以通过这种方式在不同的线程之间传递数据。 需要注意的是,ThreadLocal中的数据存储在每个线程的本地内存中,因此如果一个线程修改了存储在ThreadLocal中的值,它不会影响其他线程中的副本。这意味着ThreadLocal通常用于存储需要在多个线程之间隔离的数据。 除了set()和get()方法外,ThreadLocal还提供了remove()方法来删除当前线程中的数据副本。此外,还可以使用getAndSet()方法来获取当前线程中的值并设置新的值。 总之,ThreadLocal是一种非常有用的工具,它允许每个线程拥有自己的数据副本,从而避免了共享变量之间的冲突。它通常用于需要隔离不同线程之间的数据的情况。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值