int i = key.threadLocalHashCode & (len-1); //当前ThreadLocal hashkode且长度
for (Entry e = tab[i]; e != null;
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get(); //从table数组中拿到
if (k == key) {
e.value = value; //当前value设置给entry里面的,替换掉原值
return;
}
if (k == null) { //当前entry为空
replaceStaleEntry(key, value, i); //当前key设置进来
return;
}
}
tab[i] = new Entry(key, value);//table为空,就直接new一个
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash(); //如果长度大于threshold(阈值),重新hash
}
One possible (and common) use is when you have some object that is not thread-safe, but you want to avoid synchronizing access to that object (I’m looking at you, SimpleDateFormat). Instead, give each thread its own instance of the object. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
publicclassFoo
{
// SimpleDateFormat is not thread-safe, so give one to each thread
privatestaticfinal ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){