threadlocal的作用以及应用场景 threadlocal算是一种并发容器吧,因为他的内部是有threadlocalmap组成,threadlocal是为了解决多线程情况下变量不能被共享的问题,也就是多线程共享变量的问题。
threadlocal和lock以及synchronized的区别是:threadlocal是给每个线程分配一个变量(对象),各个线程都存有变量的副本,这样每个线程都是使用自己(变量)对象实例,使线程与线程之间进行隔离;而lock和synchronized的方式是使线程有顺序的执行。
举一个简单的例子:目前有100个学生等待签字,但是老师只有一个笔,那老师只能按顺序的分给每个学生,等待a学生签字完成然后将笔交给b学生,这就类似lock,synchronized的方式。而threadlocal是,老师直接拿出一百个笔给每个学生;再效率提高的同事也要付出一个内存消耗;也就是以空间换时间的概念
基于 spring boot + mybatis plus + vue & element 实现的后台管理系统 + 用户小程序,支持 rbac 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能
项目地址:https://gitee.com/zhijiantianya/ruoyi-vue-pro 视频教程:https://doc.iocoder.cn/video/ 使用场景 spring的事务隔离就是使用threadlocal和aop来解决的;主要是transactionsynchronizationmanager这个类;
解决simpledateformat线程不安全问题;
当我们使用simpledateformat的parse()方法的时候,parse()方法会先调用calendar.clear()方法,然后调用calendar.add()方法,如果一个线程先调用了add()方法,然后另一个线程调用了clear()方法;这时候parse()方法就会出现解析错误;如果不信我们可以来个例子:
public class simpledateformattest { private static simpledateformat simpledateformat = new simpledateformat(yyyy-mm-dd); public static void main(string[] args) { for (int i = 0; i < 50; i++) { thread thread = new thread(new runnable() { @override public void run() { dateformat(); } }); thread.start(); } } /** * 字符串转成日期类型 */ public static void dateformat() { try { simpledateformat.parse(2021-5-27); } catch (parseexception e) { e.printstacktrace(); } }} 这里我们只启动了50个线程问题就会出现,其实看巧不巧,有时候只有10个线程的情况就会出错:
exception in thread thread-40 java.lang.numberformatexception: for input string: at java.lang.numberformatexception.forinputstring(numberformatexception.java:65) at java.lang.long.parselong(long.java:601) at java.lang.long.parselong(long.java:631) at java.text.digitlist.getlong(digitlist.java:195) at java.text.decimalformat.parse(decimalformat.java:2084) at java.text.simpledateformat.subparse(simpledateformat.java:1869) at java.text.simpledateformat.parse(simpledateformat.java:1514) at java.text.dateformat.parse(dateformat.java:364) at cn.haoxy.use.lock.sdf.simpledateformattest.dateformat(simpledateformattest.java:36) at cn.haoxy.use.lock.sdf.simpledateformattest$1.run(simpledateformattest.java:23) at java.lang.thread.run(thread.java:748)exception in thread thread-43 java.lang.numberformatexception: multiple points at sun.misc.floatingdecimal.readjavaformatstring(floatingdecimal.java:1890) at sun.misc.floatingdecimal.parsedouble(floatingdecimal.java:110) at java.lang.double.parsedouble(double.java:538) at java.text.digitlist.getdouble(digitlist.java:169) at java.text.decimalformat.parse(decimalformat.java:2089) at java.text.simpledateformat.subparse(simpledateformat.java:1869) at java.text.simpledateformat.parse(simpledateformat.java:1514) at java.text.dateformat.parse(dateformat.java:364) at ............. 其实解决这个问题很简单,让每个线程new一个自己的simpledateformat,但是如果100个线程都要new100个simpledateformat吗?
当然我们不能这么做,我们可以借助线程池加上threadlocal来解决这个问题:
public class simpledateformattest { private static threadlocal local = new threadlocal() { @override //初始化线程本地变量 protected simpledateformat initialvalue() { return new simpledateformat(yyyy-mm-dd); } }; public static void main(string[] args) { executorservice es = executors.newcachedthreadpool(); for (int i = 0; i { //调用字符串转成日期方法 dateformat(); }); } es.shutdown(); } /** * 字符串转成日期类型 */ public static void dateformat() { try { //threadlocal中的get()方法 local.get().parse(2021-5-27); } catch (parseexception e) { e.printstacktrace(); } }} 这样就优雅的解决了线程安全问题;
解决过度传参问题;例如一个方法中要调用好多个方法,每个方法都需要传递参数;例如下面示例:
void work(user user) { getinfo(user); checkinfo(user); setsomething(user); log(user);} 用了threadlocal之后:
public class threadlocalstu { private static threadlocal userthreadlocal = new threadlocal(); void work(user user) { try { userthreadlocal.set(user); getinfo(); checkinfo(); something(); } finally { userthreadlocal.remove(); } } void setinfo() { user u = userthreadlocal.get(); //..... } void checkinfo() { user u = userthreadlocal.get(); //.... } void something() { user u = userthreadlocal.get(); //.... }} 每个线程内需要保存全局变量(比如在登录成功后将用户信息存到threadlocal里,然后当前线程操作的业务逻辑直接get取就完事了,有效的避免的参数来回传递的麻烦之处),一定层级上减少代码耦合度。
比如存储 交易id等信息。每个线程私有。 比如aop里记录日志需要before记录请求id,end拿出请求id,这也可以。 比如jdbc连接池(很典型的一个threadlocal用法) ....等等.... 基于 spring cloud alibaba + gateway + nacos + rocketmq + vue & element 实现的后台管理系统 + 用户小程序,支持 rbac 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能
项目地址:https://gitee.com/zhijiantianya/yudao-cloud 视频教程:https://doc.iocoder.cn/video/ 原理分析 上面我们基本上知道了threadlocal的使用方式以及应用场景,当然应用场景不止这些这只是工作中常用到的场景;下面我们对它的原理进行分析;
我们先看一下它的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);} 是不是特别简单,首先获取当前线程,用当前线程作为key,去获取threadlocalmap,然后判断map是否为空,不为空就将当前线程作为key,传入的value作为map的value值;如果为空就创建一个threadlocalmap,然后将key和value方进去;从这里可以看出value值是存放到threadlocalmap中;
然后我们看看threadlocalmap是怎么来的?先看下getmap()方法:
//在thread类中维护了threadlocals变量,注意是thread类threadlocal.threadlocalmap threadlocals = null; //在threadlocal类中的getmap()方法threadlocalmap getmap(thread t) { return t.threadlocals; } 这就能解释每个线程中都有一个threadlocalmap,因为threadlocalmap的引用在thread中维护;这就确保了线程间的隔离;
我们继续回到set()方法,看到当map等于空的时候createmap(t, value);
void createmap(thread t, t firstvalue) { t.threadlocals = new threadlocalmap(this, firstvalue); } 这里就是new了一个threadlocalmap然后赋值给threadlocals成员变量;threadlocalmap构造方法:
threadlocalmap(threadlocal firstkey, object firstvalue) { //初始化一个entry table = new entry[initial_capacity]; //计算key应该存放的位置 int i = firstkey.threadlocalhashcode & (initial_capacity - 1); //将entry放到指定位置 table[i] = new entry(firstkey, firstvalue); size = 1; //设置数组的大小 16*2/3=10,类似hashmap中的0.75*16=12 setthreshold(initial_capacity); } 这里写有个大概的印象,后面对threadlocalmap内部结构还会进行详细的讲解;
下面我们再去看一下get()方法:
public t get() { thread t = thread.currentthread(); //用当前线程作为key去获取threadlocalmap threadlocalmap map = getmap(t); if (map != null) { //map不为空,然后获取map中的entry threadlocalmap.entry e = map.getentry(this); if (e != null) { @suppresswarnings(unchecked) //如果entry不为空就获取对应的value值 t result = (t)e.value; return result; } } //如果map为空或者entry为空的话通过该方法初始化,并返回该方法的value return setinitialvalue();} get()方法和set()都比较容易理解,如果map等于空的时候或者entry等于空的时候我们看看setinitialvalue()方法做了什么事:
private t setinitialvalue() { //初始化变量值 由子类去实现并初始化变量 t value = initialvalue(); thread t = thread.currentthread(); //这里再次getmap(); threadlocalmap map = getmap(t); if (map != null) map.set(this, value); else //和set()方法中的 createmap(t, value); return value; } 下面我们再去看一下threadlocal中的initialvalue()方法:
protected t initialvalue() { return null; } 设置初始值,由子类去实现;就例如我们上面的例子,重写threadlocal类中的initialvalue()方法:
private static threadlocal local = new threadlocal() { @override //初始化线程本地变量 protected simpledateformat initialvalue() { return new simpledateformat(yyyy-mm-dd); } }; createmap()方法和上面set()方法中createmap()方法同一个,就不过多的叙述了;剩下还有一个removve()方法
public void remove() { threadlocalmap m = getmap(thread.currentthread()); if (m != null) //2. 从map中删除以当前threadlocal实例为key的键值对 m.remove(this); } 源码的讲解就到这里,也都比较好理解,下面我们看看threadlocalmap的底层结构
threadlocalmap的底层结构 上面我们已经了解了threadlocal的使用场景以及它比较重要的几个方法;下面我们再去它的内部结构;经过上的源码分析我们可以看到数据其实都是存放到了threadlocal中的内部类threadlocalmap中;而threadlocalmap中又维护了一个entry对象,也就说数据最终是存放到entry对象中的;
static class threadlocalmap { static class entry extends weakreference { /** the value associated with this threadlocal. */ object value; entry(threadlocal k, object v) { super(k); value = v; } } threadlocalmap(threadlocal firstkey, object firstvalue) { table = new entry[initial_capacity]; int i = firstkey.threadlocalhashcode & (initial_capacity - 1); table[i] = new entry(firstkey, firstvalue); size = 1; setthreshold(initial_capacity); } // ....................} entry的构造方法是以当前线程为key,变量值object为value进行存储的;在上面的源码中threadlocalmap的构造方法中也涉及到了entry;看到entry是一个数组;初始化长度为initial_capacity = 16;因为 entry 继承了 weakreference,在 entry 的构造方法中,调用了 super(k)方法就会将 threadlocal 实例包装成一个 weakreferenece。这也是threadlocal会产生内存泄露的原因;
内存泄露产生的原因 如图所示存在一条引用链: thread ref->thread->threadlocalmap->entry->key:value,经过上面的讲解我们知道threadlocal作为key,但是被设置成了弱引用,弱引用在jvm垃圾回收时是优先回收的,就是说无论内存是否足够弱引用对象都会被回收;弱引用的生命周期比较短;当发生一次gc的时候就会变成如下:
treadlocalmap中出现了key为null的entry,就没有办法访问这些key为null的entry的value,如果线程迟迟不结束(也就是说这条引用链无意义的一直存在)就会造成value永远无法回收造成内存泄露;如果当前线程运行结束thread,threadlocalmap,entry之间没有了引用链,在垃圾回收的时候就会被回收;但是在开发中我们都是使用线程池的方式,线程池的复用不会主动结束;所以还是会存在内存泄露问题;
解决方法也很简单,就是在使用完之后主动调用remove()方法释放掉;
解决hash冲突 记得在大学学习数据结构的时候学习了很多种解决hash冲突的方法;例如:
线性探测法(开放地址法的一种): 计算出的散列地址如果已被占用,则按顺序找下一个空位。如果找到末尾还没有找到空位置就从头重新开始找;
二次探测法(开放地址法的一种)
链地址法:链地址是对每一个同义词都建一个单链表来解决冲突,hashmap采用的是这种方法;
多重hash法: 在key冲突的情况下多重hash,直到不冲突为止,这种方式不易产生堆积但是计算量太大;
公共溢出区法: 这种方式需要两个表,一个存基础数据,另一个存放冲突数据称为溢出表;
上面的图片都是在网上找到的一些资料,和大学时学习时的差不多我就直接拿来用了;也当自己复习了一遍;
介绍了那么多解决hash冲突的方法,那threadlocalmap使用的哪一种方法呢?我们可以看一下源码:
private void set(threadlocal key, object value) { entry[] tab = table; int len = tab.length; //根据hashcode & 数组长度 计算出数组该存放的位置 int i = key.threadlocalhashcode & (len-1); //遍历entry数组中的元素 for (entry e = tab[i]; e != null; e = tab[i = nextindex(i, len)]) { threadlocal k = e.get(); //如果这个entry对象的key正好是即将设置的key,那么就刷新entry中的value; if (k == key) { e.value = value; return; } // entry!=null,key==null时,说明threadlcoal这key已经被gc了,这里就是上面说到 //会有内存泄露的地方,当然作者也知道这种情况的存在,所以这里做了一个判断进行解决脏的 //entry(数组中不想存有过时的entry),但是也不能解决泄露问题,因为旧value还存在没有消失 if (k == null) { //用当前插入的值代替掉这个key为null的“脏”entry replacestaleentry(key, value, i); return; } } //新建entry并插入table中i处 tab[i] = new entry(key, value); int sz = ++size; if (!cleansomeslots(i, sz) && sz >= threshold) rehash(); } 从这里我们可以看出使用的是线性探测的方式来解决hash冲突!
源码中通过nextindex(i, len)方法解决 hash 冲突的问题,该方法为((i + 1 < len) ? i + 1 : 0);,也就是不断往后线性探测,直到找到一个空的位置,当到哈希表末尾的时候还没有找到空位置再从 0 开始找,成环形!
使用threadlocal时对象存在哪里? 在java中,栈内存归属于单个线程,每个线程都会有一个栈内存,其存储的变量只能在其所属线程中可见,即栈内存可以理解成线程的私有变量,而堆内存中的变量对所有线程可见,可以被所有线程访问!
那么threadlocal的实例以及它的值是不是存放在栈上呢?其实不是的,因为threadlocal的实例实际上也是被其创建的类持有,(更顶端应该是被线程持有),而threadlocal的值其实也是被线程实例持有,它们都是位于堆上,只是通过一些技巧将可见性修改成了线程可见。
ADI单芯片解决方案应对医疗设备高清图像采集
滤波器的主要参数介绍
扬尘在线监控系统厂家的详细介绍@三体推荐
geant4在manjaro/archlinux系统下的安装方法
新唐科技推出KM1M4BF系列MCU马达和PFC控制器
ThreadLocal的作用以及应用场景
自由现金将如何在全球范围内实现密码经济
LoRa 联盟实现了 LoRa 芯片供应的多元化
iQOO十一月大放异彩,多款机型已经成为爆款!
ESD实时监测报警系统的构成
探讨数字智能变电站变压器保护方案
微雪电子STM32 Cortex M4开发板 Core407Z简介
带频率响应补偿的MEMS振动分析仪
中兴事件博弈仍在继续,损失或超200亿人民币
部分单相电动机的绕组数据汇集
无人机与载人飞机结合建立超视距视觉实验走廊
Space X重型火箭“SN8”发射高空测试圆满成功
雷蛇发布清姬专业版全高清USB网络摄像头
曝三星将在下月发布Galaxy Note 10 Lite和Galaxy S10 Lite
三星华为猛发力,联想也“凑热闹”,折叠屏手机首发将发落谁家?