ThreadLocal系列-ThreadLocalMap源码

2023-12-12 00:01

本文主要是介绍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;}}
}

这篇关于ThreadLocal系列-ThreadLocalMap源码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/482549

相关文章

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

科研绘图系列:R语言扩展物种堆积图(Extended Stacked Barplot)

介绍 R语言的扩展物种堆积图是一种数据可视化工具,它不仅展示了物种的堆积结果,还整合了不同样本分组之间的差异性分析结果。这种图形表示方法能够直观地比较不同物种在各个分组中的显著性差异,为研究者提供了一种有效的数据解读方式。 加载R包 knitr::opts_chunk$set(warning = F, message = F)library(tidyverse)library(phyl

【生成模型系列(初级)】嵌入(Embedding)方程——自然语言处理的数学灵魂【通俗理解】

【通俗理解】嵌入(Embedding)方程——自然语言处理的数学灵魂 关键词提炼 #嵌入方程 #自然语言处理 #词向量 #机器学习 #神经网络 #向量空间模型 #Siri #Google翻译 #AlexNet 第一节:嵌入方程的类比与核心概念【尽可能通俗】 嵌入方程可以被看作是自然语言处理中的“翻译机”,它将文本中的单词或短语转换成计算机能够理解的数学形式,即向量。 正如翻译机将一种语言

Java ArrayList扩容机制 (源码解读)

结论:初始长度为10,若所需长度小于1.5倍原长度,则按照1.5倍扩容。若不够用则按照所需长度扩容。 一. 明确类内部重要变量含义         1:数组默认长度         2:这是一个共享的空数组实例,用于明确创建长度为0时的ArrayList ,比如通过 new ArrayList<>(0),ArrayList 内部的数组 elementData 会指向这个 EMPTY_EL

如何在Visual Studio中调试.NET源码

今天偶然在看别人代码时,发现在他的代码里使用了Any判断List<T>是否为空。 我一般的做法是先判断是否为null,再判断Count。 看了一下Count的源码如下: 1 [__DynamicallyInvokable]2 public int Count3 {4 [__DynamicallyInvokable]5 get

工厂ERP管理系统实现源码(JAVA)

工厂进销存管理系统是一个集采购管理、仓库管理、生产管理和销售管理于一体的综合解决方案。该系统旨在帮助企业优化流程、提高效率、降低成本,并实时掌握各环节的运营状况。 在采购管理方面,系统能够处理采购订单、供应商管理和采购入库等流程,确保采购过程的透明和高效。仓库管理方面,实现库存的精准管理,包括入库、出库、盘点等操作,确保库存数据的准确性和实时性。 生产管理模块则涵盖了生产计划制定、物料需求计划、

flume系列之:查看flume系统日志、查看统计flume日志类型、查看flume日志

遍历指定目录下多个文件查找指定内容 服务器系统日志会记录flume相关日志 cat /var/log/messages |grep -i oom 查找系统日志中关于flume的指定日志 import osdef search_string_in_files(directory, search_string):count = 0

Spring 源码解读:自定义实现Bean定义的注册与解析

引言 在Spring框架中,Bean的注册与解析是整个依赖注入流程的核心步骤。通过Bean定义,Spring容器知道如何创建、配置和管理每个Bean实例。本篇文章将通过实现一个简化版的Bean定义注册与解析机制,帮助你理解Spring框架背后的设计逻辑。我们还将对比Spring中的BeanDefinition和BeanDefinitionRegistry,以全面掌握Bean注册和解析的核心原理。

音视频入门基础:WAV专题(10)——FFmpeg源码中计算WAV音频文件每个packet的pts、dts的实现

一、引言 从文章《音视频入门基础:WAV专题(6)——通过FFprobe显示WAV音频文件每个数据包的信息》中我们可以知道,通过FFprobe命令可以打印WAV音频文件每个packet(也称为数据包或多媒体包)的信息,这些信息包含该packet的pts、dts: 打印出来的“pts”实际是AVPacket结构体中的成员变量pts,是以AVStream->time_base为单位的显