ThreadLocal系列-ThreadLocalMap源码

1.ThreadLocalMap.Entry

key:指向key的是弱引用

value:强引用

public class ThreadLocal<T> {static class ThreadLocalMap {/*** The entries in this hash map extend WeakReference, using* its main ref field as the key (which is always a* ThreadLocal object).  Note that null keys (i.e. entry.get()* == null) mean that the key is no longer referenced, so the* entry can be expunged from table.  Such entries are referred to* as "stale entries" in the code that follows.*/static class Entry extends WeakReference<ThreadLocal<?>> {/** The value associated with this ThreadLocal. */Object value;Entry(ThreadLocal<?> k, Object v) {super(k);  //指向key的弱引用value = v; //指向value的是强引用}}}
}

2.hash计算

  • nextHashCode是static的,说明是ThreadLocal类共用
  • 在上一个ThreadLocal的hash的基础上增加HASH_INCREMENT
public class ThreadLocal<T> {//所有ThreadLocal类公用private static AtomicInteger nextHashCode = new AtomicInteger();private static final int HASH_INCREMENT = 0x61c88647;private final int threadLocalHashCode = nextHashCode();//每次在上一个hash的基础上增加HASH_INCREMENTprivate static int nextHashCode() {return nextHashCode.getAndAdd(HASH_INCREMENT);}
}

HASH_INCREMENT 的值是 0x61c88647,它是黄金分割比例乘以 2^31,这样可以使得步长增量更加分散,减小碰撞的概率,提高 ThreadLocal 的性能。

黄金分割率是一个数学和艺术上的常数,通常用希腊字母 φ(phi)表示,其近似值为1.618033988749895。

3.怎么处理hash冲突

ThreadLocalMap 使用线性探测法(linear probing)来处理哈希冲突。线性探测法是一种解决哈希冲突的简单方法,其中如果一个槽已经被占用,就线性地查找下一个可用的槽,直到找到一个可用槽为止。

Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1); //这里计算index跟HashMap一样

如果i被占用,则用nextIndex(i, len)计算下一个索引,看是否被占用

public class ThreadLocal<T> {static class ThreadLocalMap {/*** The table, resized as necessary.* table.length MUST always be a power of two.*/private Entry[] table;/*** Increment i modulo len.* 每次i+1,如果i+1<len,则返回0*/private static int nextIndex(int i, int len) {return ((i + 1 < len) ? i + 1 : 0);}/*** Set the value associated with key.** @param key the thread local object* @param value the value to be set*/private void set(ThreadLocal<?> key, Object value) {// We don't use a fast path as with get() because it is at// least as common to use set() to create new entries as// it is to replace existing ones, in which case, a fast// path would fail more often than not.Entry[] tab = table;int len = tab.length;int i = key.threadLocalHashCode & (len-1); //这里计算index跟HashMap一样//下一个元素:i+1,如果i+1越界,怎为0for (Entry e = tab[i]; e != null; e = tab[i = nextIndex(i, len)]) {ThreadLocal<?> k = e.get(); //获取keyif (k == key) { //key相等e.value = value; //更新value的值return;}if (k == null) {//说明这里放入的是无效数据,可以放入新数据replaceStaleEntry(key, value, i);//放入数据,再做些无效数据清理工作return;}//e不为null;k不为null;说明被正常的元素占用了,则到下一个索引}//tab[i]为null,退出了循环tab[i] = new Entry(key, value); //放入数组int sz = ++size;//如果没有移除数据,同时size大于thresholdif (!cleanSomeSlots(i, sz) && sz >= threshold){rehash(); //扩容}}}
}

4.扩容

  • 先清理所有的stale数据;
  • 如果size大于等于threshold*3/4,进行扩容;
public class ThreadLocal<T> {static class ThreadLocalMap {private void rehash() {expungeStaleEntries(); //清理stale数据// Use lower threshold for doubling to avoid hysteresis//数据大小大于或者等于threshold的3/4后,进行扩容if (size >= threshold - threshold / 4)resize();}}
}
4.1.expungeStaleEntries-清理所有的stale数据

循环遍历执行expungeStaleEntry方法;

expungeStaleEntry方法:

(1)从table清除位于staleSlot的Entry;

(2)从staleSlot往后遍历table,直到table[i]为null

        如果table[i]为stale元素,从table清除该元素;

        如果table[i]不为stale元素,计算table[i]中的Entry本来应该放入的index,从那个index开始往后找Entry应该放入的位置A,将该Entry放入位置A;

 expungeStaleEntries

public class ThreadLocal<T> {static class ThreadLocalMap {/*** 清除table里面的所有无效数据()*/private void expungeStaleEntries() {Entry[] tab = table;int len = tab.length;for (int j = 0; j < len; j++) {Entry e = tab[j];if (e != null && e.get() == null){//e不为null且key为nullexpungeStaleEntry(j);}}}private int expungeStaleEntry(int staleSlot) {Entry[] tab = table;int len = tab.length;// expunge entry at staleSlottab[staleSlot].value = null; //value设为nulltab[staleSlot] = null;  //entry设为nullsize--; //size减1// Rehash until we encounter nullEntry e;int i;for (i = nextIndex(staleSlot, len); (e = tab[i]) != null;i = nextIndex(i, len)) {ThreadLocal<?> k = e.get();if (k == null) {//如果元素不为null,但是key为nulle.value = null;tab[i] = null;size--;} else {//不是stale元素的话,重新将这个元素放到合适的位置int h = k.threadLocalHashCode & (len - 1); //计算indexif (h != i) {//本来应该放在h的位置,因为冲突的关系被放到了i//h->>>>>>>>>>>i 看这中间有没有为null的tab[i] = null;// Unlike Knuth 6.4 Algorithm R, we must scan until// null because multiple entries could have been stale.while (tab[h] != null) {//从h开始找e为null的indexh = nextIndex(h, len);}tab[h] = e; //把e放在合适的index}}}return i; //返回的i是Entry为null的索引}}
}
4.2.ThreadLocalMap.resize-扩容

扩容:

新table的长度为老table长度的2倍;

遍历老table:

        table[j]不为null:

                key为null,设置value为null;

                key不为null,根据新table的length计算index,将该元素放入合适的位置;

public class ThreadLocal<T> {static class ThreadLocalMap {private void resize() {Entry[] oldTab = table;int oldLen = oldTab.length;int newLen = oldLen * 2; //新len为老len的2倍Entry[] newTab = new Entry[newLen];int count = 0;for (int j = 0; j < oldLen; ++j) {Entry e = oldTab[j];if (e != null) {ThreadLocal<?> k = e.get();if (k == null) {//stale元素e.value = null; // Help the GC} else {int h = k.threadLocalHashCode & (newLen - 1); //重新计算indexwhile (newTab[h] != null){//找到该元素该放的位置h = nextIndex(h, newLen);}newTab[h] = e;count++;}}}setThreshold(newLen); //更新thresholdsize = count;table = newTab;}}
}

5.ThreadLocalMap.replaceStaleEntry

public class ThreadLocal<T> {/*** ThreadLocalMap is a customized hash map suitable only for* maintaining thread local values. No operations are exported* outside of the ThreadLocal class. The class is package private to* allow declaration of fields in class Thread.  To help deal with* very large and long-lived usages, the hash table entries use* WeakReferences for keys. However, since reference queues are not* used, stale entries are guaranteed to be removed only when* the table starts running out of space.*/static class ThreadLocalMap {/*** Decrement i modulo len.*/private static int prevIndex(int i, int len) {return ((i - 1 >= 0) ? i - 1 : len - 1);}/*** Replace a stale entry encountered during a set operation* with an entry for the specified key.  The value passed in* the value parameter is stored in the entry, whether or not* an entry already exists for the specified key.** As a side effect, this method expunges all stale entries in the* "run" containing the stale entry.  (A run is a sequence of entries* between two null slots.)** @param  key the key* @param  value the value to be associated with key* @param  staleSlot index of the first stale entry encountered while*         searching for key.*/private void replaceStaleEntry(ThreadLocal<?> key, Object value, int staleSlot) {Entry[] tab = table;int len = tab.length;Entry e;// Back up to check for prior stale entry in current run.// We clean out whole runs at a time to avoid continual// incremental rehashing due to garbage collector freeing// up refs in bunches (i.e., whenever the collector runs).int slotToExpunge = staleSlot;//每次i-1,直到i-1<0时,i=len-1//跳出遍历:tab[i]为null//往前找stale元素,直到Entry为nullfor (int i = prevIndex(staleSlot, len); (e = tab[i]) != null;i = prevIndex(i, len)){if (e.get() == null){slotToExpunge = i;}}// Find either the key or trailing null slot of run, whichever// occurs first//往后,直到Entry为nullfor (int i = nextIndex(staleSlot, len);(e = tab[i]) != null;i = nextIndex(i, len)) {ThreadLocal<?> k = e.get();// If we find key, then we need to swap it// with the stale entry to maintain hash table order.// The newly stale slot, or any other stale slot// encountered above it, can then be sent to expungeStaleEntry// to remove or rehash all of the other entries in run.if (k == key) { //往后找到个key相等的e.value = value; //更新valuetab[i] = tab[staleSlot]; //那i的位置是stale元素tab[staleSlot] = e; //把元素放到staleSlot位置// Start expunge at preceding stale entry if it existsif (slotToExpunge == staleSlot){slotToExpunge = i;}cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);return;}// If we didn't find stale entry on backward scan, the// first stale entry seen while scanning for key is the// first still present in the run.if (k == null && slotToExpunge == staleSlot){slotToExpunge = i;}}// If key not found, put new entry in stale slottab[staleSlot].value = null;tab[staleSlot] = new Entry(key, value); //放入元素// If there are any other stale entries in run, expunge themif (slotToExpunge != staleSlot){cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);}}   }        
}

6.ThreadLocalMap.cleanSomeSlots

每次n=n/2来循环调用expungeStaleEntry清理stale数据

public class ThreadLocal<T> {static class ThreadLocalMap {private boolean cleanSomeSlots(int i, int n) {boolean removed = false;Entry[] tab = table;int len = tab.length;do {i = nextIndex(i, len);//从i往后找stale的元素Entry e = tab[i];if (e != null && e.get() == null) {//stale元素n = len;removed = true;i = expungeStaleEntry(i);}} while ( (n >>>= 1) != 0); //从方法的注释来看,每次对n/2是为了在清除无用数据和速 //度之间做个平衡,这样既清理了无用数据,又不会因为清理 //太多无用数据,耽误了插入数据的时间return removed;}}
}

7.ThreadLocalMap.getEntry

public class ThreadLocal<T> {static class ThreadLocalMap {private Entry getEntry(ThreadLocal<?> key) {int i = key.threadLocalHashCode & (table.length - 1);Entry e = table[i];// Android-changed: Use refersTo()if (e != null && e.refersTo(key)){//i这个位置刚好放的Entry的key一致return e;} else {return getEntryAfterMiss(key, i, e);}}}
}

getEntryAfterMiss

 往后遍历,直到Entry为null

  • 如果key相等,返回Entry;
  • 如果key为null,是stale元素,清理一下;
  • 最终没找到,就返回null;
public class ThreadLocal<T> {static class ThreadLocalMap {private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {Entry[] tab = table;int len = tab.length;while (e != null) {// Android-changed: Use refersTo()if (e.refersTo(key)){ //key相等return e;}if (e.refersTo(null)){expungeStaleEntry(i); //清理} else{i = nextIndex(i, len); //下一个索引}e = tab[i];}return null;}}
}

8.ThreadLocalMap构造方法

初始化数组table,初始容量为16;

计算index,在table[index]处放入new Entry(key, value);

更新threshold为10;

public class ThreadLocal<T> {static class ThreadLocalMap {/*** The table, resized as necessary.* table.length MUST always be a power of two.*/private Entry[] table;/*** The number of entries in the table.*/private int size = 0;/*** The initial capacity -- MUST be a power of two.*/private static final int INITIAL_CAPACITY = 16;/*** The next size value at which to resize.*/private int threshold; // Default to 0/*** Construct a new map initially containing (firstKey, firstValue).* ThreadLocalMaps are constructed lazily, so we only create* one when we have at least one entry to put in it.*/ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {table = new Entry[INITIAL_CAPACITY]; //默认数组容量大小为16int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1); //计算indextable[i] = new Entry(firstKey, firstValue);//放入数组size = 1; //更新sizesetThreshold(INITIAL_CAPACITY); //设置threshold 16*2/3 = 10}/*** Set the resize threshold to maintain at worst a 2/3 load factor.*/private void setThreshold(int len) {threshold = len * 2 / 3;}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/214456.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

32、卷积参数 - 长宽方向的公式推导

有了前面三节的卷积基础 padding, stride, dilation 之后,大概就可以了解一个卷积算法的全貌了。 一个完整的卷积包含的输入和输出有: 输入图像,表示为[n, hi, wi, ci] 卷积核,表示为[co, kh, kw, ci] 输出特征图,表示为[n, ho, wo, co] 以上为卷积算法的两个输入 tensor…

【持更】python数据处理-学习笔记

1、读取excel /csv及指定sheet&#xff1a; pd.read_excel("路径",sheetname"xx") 修改列名df.rename 修改字符串类型到数字 pandas.to_numeric&#xff08;&#xff09; 2、删除drop、去重drop_duplicates &#xff08;1&#xff09;空值所在行/列 行&am…

Redis分布式锁有什么缺陷?

Redis分布式锁有什么缺陷&#xff1f; Redis 分布式锁不能解决超时的问题&#xff0c;分布式锁有一个超时时间&#xff0c;程序的执行如果超出了锁的超时时间就会出现问题。 1.Redis容易产生的几个问题&#xff1a; 2.锁未被释放 3.B锁被A锁释放了 4.数据库事务超时 5.锁过期了…

centos 7 卸载图形化界面步骤记录

centos7 服务器操作系统&#xff0c;挺小一配置&#xff0c;装了图形化界面&#xff0c;现在运行程序的时候跑不动了&#xff0c;我想这图形界面也没啥用&#xff0c;卸载了算了&#xff01; 卸载步骤 yum grouplist 查询已经安装的组件 可以看到 图形化界面 等是以分组存在的…

深入理解Spring IOC的工作流程

理解Spring IOC&#xff08;Inversion of Control&#xff09;的工作流程是理解Spring框架的核心之一。下面是Spring IOC的基本工作流程&#xff1a; 配置&#xff1a; 开发者通过XML配置文件、Java配置类或者注解等方式&#xff0c;定义应用中的Bean以及它们之间的依赖关系。这…

TCP数据粘包的处理

TCP数据粘包的处理 背锅侠TCP解决方案2.1 发送端2.2 接收端 背锅侠TCP 在前面介绍套接字通信的时候说到了TCP是传输层协议&#xff0c;它是一个面向连接的、安全的、流式传输协议。因为数据的传输是基于流的所以发送端和接收端每次处理的数据的量&#xff0c;处理数据的频率可…

Qt练习题

1.使用手动连接&#xff0c;将登录框中的取消按钮使用qt4版本的连接到自定义的槽函数中&#xff0c;在自定义的槽函数中调用关闭函数 将登录按钮使用qt5版本的连接到自定义的槽函数中&#xff0c;在槽函数中判断ui界面上输入的账号是否为"admin"&#xff0c;密码是否…

代码随想录 96. 不同的二叉搜索树

题目 给你一个整数 n &#xff0c;求恰由 n 个节点组成且节点值从 1 到 n 互不相同的 二叉搜索树 有多少种&#xff1f;返回满足题意的二叉搜索树的种数。 示例 1&#xff1a; 输入&#xff1a;n 3 输出&#xff1a;5 示例 2&#xff1a; 输入&#xff1a;n 1 输出&#xff1…

【Angular开发】Angular 16发布:发现前7大功能

Angular 于2023年5月3日发布了主要版本升级版Angular 16。作为一名Angular开发人员&#xff0c;我发现这次升级很有趣&#xff0c;因为与以前的版本相比有一些显著的改进。 因此&#xff0c;在本文中&#xff0c;我将讨论Angular 16的前7个特性&#xff0c;以便您更好地理解。…

机器学习基础介绍

百度百科&#xff1a; 机器学习是一门多领域交叉学科&#xff0c;涉及概率论、统计学、逼近论、凸分析、算法复杂度理论等多门学科。专门研究计算机怎样模拟或实现人类的学习行为&#xff0c;以获取新的知识或技能&#xff0c;重新组织已有的知识结构使之不断改善自身的性能。 …

手工酸奶店如何选址?开在哪里比较合适?

手工酸奶店是一个非常受欢迎的创业项目&#xff0c;但想要成功开店&#xff0c;选址是非常重要的。 本人开酸奶店5年时间&#xff0c;下面我将为大家分享一些选址的小技巧&#xff0c;希望对大家有所帮助。&#xff08;可以点赞收藏&#xff0c;方便以后随时查阅&#xff09; …

入职字节外包一个月,我离职了。。。

有一种打工人的羡慕&#xff0c;叫做“大厂”。 真是年少不知大厂香&#xff0c;错把青春插稻秧。 但是&#xff0c;在深圳有一群比大厂员工更庞大的群体&#xff0c;他们顶着大厂的“名”&#xff0c;做着大厂的工作&#xff0c;还可以享受大厂的伙食&#xff0c;却没有大厂…

12.11 C++ 作业

完善对话框&#xff0c;点击登录对话框&#xff0c;如果账号和密码匹配&#xff0c;则弹出信息对话框&#xff0c;给出提示”登录成功“&#xff0c;提供一个Ok按钮&#xff0c;用户点击Ok后&#xff0c;关闭登录界面&#xff0c;跳转到其他界面 如果账号和密码不匹配&#xf…

树根研习社|数据为王,洞察“工业数据采集”背后的价值与实践

一、工业数据采集是什么&#xff1f; 数据采集是将各种信息传感设备通过网络结合起来&#xff0c;实现任何时间、任何地点&#xff0c;人、机、物的互联互通。数据采集的主要的作用是&#xff1a; “翻译官”&#xff1a;不同程序语言的设备数据通过协议解析“翻译”为上层系…

淘宝权益玩法平台的Serverless化实践

通过对权益玩法平台现有业务应用的Serverless化改造&#xff0c;权益团队在双十一期间完美地支撑了业务需求&#xff0c;在研发效率、运维保障等方面都体现出了很高的价值和收益。 项目背景 淘宝权益平台是负责淘宝权益营销的核心团队&#xff0c;团队除了负责拉菲权益平台外&a…

1.cloud-微服务架构编码构建

1.微服务cloud整体聚合父工程 1.1 New Project 1.2 Maven选版本 1.3 字符编码 1.4 注解生效激活 主要为lombok中的Data 1.5 java编译版本选8 1.6 File Type过滤 *.hprof;*.idea;*.iml;*.pyc;*.pyo;*.rbc;*.yarb;*~;.DS_Store;.git;.hg;.svn;CVS;__pycache__;_svn;vssver.scc;v…

Nginx配置文件的基本用法

Nginx简介 1.1概述 Nginx是一个高性能的HTTP和反向代理服务器。 是一款轻量级的高性能的web服务器/反向代理服务器/电子邮件&#xff08;IMAP/POP3&#xff09;代理服务器 单台物理服务器可支持30 000&#xff5e;50 000个并发请求。 1.2Nginx和Apache的优缺点 &#xff…

mybatis数据输出-insert操作时获取自增列的值给对应的属性赋值

jdbc-修改 水果库存系统的 BaseDao 的 executeUpdate 方法支持返回自增列-CSDN博客 1、建库建表 CREATE DATABASE mybatis-example;USE mybatis-example;CREATE TABLE t_emp(emp_id INT AUTO_INCREMENT,emp_name CHAR(100),emp_salary DOUBLE(10,5),PRIMARY KEY(emp_id) );INSE…

王炸升级!PartyRock 10分钟构建 AI 应用

前言 一年一度的亚马逊云科技的 re:Invent 可谓是全球云计算、科技圈的狂欢&#xff0c;每次都能带来一些最前沿的方向标&#xff0c;这次也不例外。在看完一些 keynote 和介绍之后&#xff0c;我也去亲自体验了一些最近发布的内容。其中让我感受最深刻的无疑是 PartyRock 了。…

基于SSM的健身房预约系统设计与实现

末尾获取源码 开发语言&#xff1a;Java Java开发工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;Vue 数据库&#xff1a;MySQL5.7和Navicat管理工具结合 服务器&#xff1a;Tomcat8.5 开发软件&#xff1a;IDEA / Eclipse 是否Maven项目&#xff1a;是 目录…