ThreadLocal存储数据并不是直接存储数据,而是自己作为key将value存储到ThreadLocal自带的ThreadLocalMap中。ThreadLocalMap中负责存储键值对的数据结构为一维数组。
这篇文章就来分析一下,ThreadLocalMap是如何进行hash取值,并如何解决碰撞问题。
从下面代码可以看出键值对在数组中的位置由当前数组的大小len以及作为key的ThreadLocal对象的threadLocalHashCode来确定。
在2代码段中,key的threadLocalHashCode依赖于 nextHashCode()函数。这个函数在一个AtomicInteger相加,每次新建一个ThreadLocal对象就会取一次hash,在nextHashCode基础上加上 0x61c88647。
//1.
int i = key.threadLocalHashCode & (len-1);
//2.
private final int threadLocalHashCode = nextHashCode();
//3.
private static int nextHashCode() {
return nextHashCode.getAndAdd(HASH_INCREMENT);
}
//4.
private static AtomicInteger nextHashCode =
new AtomicInteger();
//5.
private static final int HASH_INCREMENT = 0x61c88647;
接下来我们来测试下这个hash方法。
package

331

被折叠的 条评论
为什么被折叠?



